Suppose you have script A: defines a library with:
class MathFunctions { add(a, b) => { return a+b; } }
And you have script B: reuses MathFunctions somehow:
const mf = import MathFunctions;
console.log(mf.add(2, 2));
And you want to execute B in vm context, importing A.
What is the best way to do this with untrusted code?
Similar question here: https://github.com/patriksimek/vm2/issues/121
The node import system (
const foo = require('foo');
) works by running your code through a preprocessor that wraps it in a function and passes inrequire, module, exports
you can replicate that effect by running your code through a preprocessor as well. Fortunately there are plenty available since the browser also lacks modules. So any of the module preprocessors for browsers (eg webpack) will do the trick.So somethings like
new VM().run(webpack('./moduleB.js'))