'How to make the `import` statement work properly inside the code created using the node:vm module?

In our project we have the custom console object which is used as a logger.
So we need to replace the default console.
For this purpose we decided to use the vm module.
But we are facing the problem while using imports inside the code created with vm.Script:

application.js:

import path from 'path';

console.log(path.resolve('./apps'));

main.js:

const context = {
  console,
  global: {},
  module: {},
  exports: {},
  require,
};
context.global = global;

const sandbox = vm.createContext(context);
const fileName = './application.js';
const src = await fsp.readFile(fileName, 'utf8');
const script = new vm.Script(`module.exports = () => {\n${src}\n};`);
const execute = script.runInNewContext(sandbox);

execute();

Output:
Error: Cannot find module 'path'

Question:
How to make imports work properly inside the application.js file?



Solution 1:[1]

Do not use a new vm.Script if you want to create a module. Use a new vm.Module instead! Notice that the API is still experimental though.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bergi