Using the dynamic import inside the `module.link()` callback causes an error

Viewed 26

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:

  1. Create the module called app by instantiating the vm.SourceTextModule class:

     const app = new vm.SourceTextModule(`import path from 'path';`);
    
  2. 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 app module to it:

     await app.link(linker);
    
  3. 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?

0 Answers
Related