In our project we need to use the vm.Module (to run the source code in the custom context).
Let's say the source code is: import path from 'path';
According to the Node.js documentation using a vm.Module object requires three distinct steps: creation/parsing, linking, and evaluation.
Let me try to follow the above steps:
Create the module called
appby instantiating thevm.SourceTextModuleclass:const app = new vm.SourceTextModule(`import path from 'path';`);Define the linking callback (the "linker"):
async function linker(specifier, referencingModule) { console.dir({ specifier, referencingModule }); // (1) const mod = await import(specifier); // (2) throws an Error console.dir(mod); // (3) never executed const exportNames = Object.keys(mod); const imported = new vm.SyntheticModule( exportNames, () => { exportNames.forEach((key) => imported.setExport(key, mod[key])); }, { identifier: specifier, context: referencingModule.context } ); return imported; }Now we can "link" the imported dependencies of the
appmodule to it:await app.link(linker);And finally evaluate the Module:
await app.evaluate();
Results:
Line (1) outputs the next debugging log:
{
specifier: 'path',
referencingModule: SourceTextModule {
status: 'linking',
identifier: 'vm:module(0)',
context: undefined
}
}
So as for now everything works as expected, now we just need to use the dynamic import to import the path module, but:
Line (2) causes an error:
Error: Cannot find module 'path'
Line (3) never executed.
Question:
What i am missing and how to make dynamic import in line (2) work?