In vm2 how to make the global/sandbox object available in imported modules?
05:18 12 Jan 2026

I can define VM's global properties/functions using 'sandbox':

const vm: any = new NodeVM({sandbox: {myGlobFn: () => 'abc'}, ... });
vm.run('console.log(myGlobFn());');

But can I use somehow the sandbox properties/functions in a required modules?

// mylib.js
module.exports = {
    myFn: function() {console.log(myGlobProp());}
}
const vm: any = new NodeVM({sandbox: {myGlobFn: () => 'abc'}, require: true, ... });
vm.run(`
  const { myFn } = require('mylib');
  console.log(myGlobFn());
`);

the above code throws error:

ReferenceError: myGlobFn is not defined
node-vm2