Dynamic module loader





Suppose you have a modular application that you want to extend with plugins, then you can use this module to load modules dynamically.
``typescript
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
})();
`
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.
`typescript
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
})();
``
See online documentation for detailed API description.