@krlwlfrt/dml
v3.0.3
Published
Dynamic module loader
Maintainers
Readme
@krlwlfrt/dml
Example usage
Suppose you have a modular application that you want to extend with plugins, then you can use this module to load modules dynamically.
import { loadModules } from '@krlwlfrt/dml';
import { join } from 'node:path';
(async () => {
// set up your application
const pluginDirectory = join(__dirname, 'plugins');
// load plugins
const modules = await loadModules(pluginDirectory);
console.log(modules);
// your application logic here
})();Hooks
The main functions loadModules and loadModule have an optional argument called hooks.
You can pass two hooks that fire just before loading a module and afterwards.
import { loadModules } from '@krlwlfrt/dml';
import { join } from 'node:path';
(async () => {
// set up your application
const pluginDirectory = join(__dirname, 'plugins');
// load plugins
const modules = await loadModules(pluginDirectory, false, {
afterLoad: async (loadedModule) => {
console.info(`Loaded plugin ${loadedModule.path} with size ${loadedModule.size}.`);
},
beforeLoad: async (pathToLoad) => {
// do not load modules, that contain 'foo' in their path
if (/foo/.test(pathToLoad)) {
return false;
}
return true;
},
});
console.log(modules);
// your application logic here
})();
Documentation
See online documentation for detailed API description.
