vm模块允许在V8虚拟机上下文中编译和运行代码。但是不是安全机制,如果有沙箱(sandbox)需求,可以考虑https://github.com/patriksimek/vm2。

在VM环境中使用ECMAScript modules,即在VM环境中可以用import代替require引入某个模块,避免Cannot use import statement outside a module错误,也可以用export代替module.exports。

我的使用场景:

通过Node.js在VM环境使用ECMAScript modules之目的,是为了构建一个虚拟环境(可控的上下文内容)动态执行一些代码,方便在复杂系统中构建小型脚本动态的快速验证一些想法。

在https://github.com/yi-ge/api-proxy这个小项目中也有用到vm模块。