要求()从string到对象

假设我有一个string中的js文件的内容。 此外,假设它有一个exports['default'] = function() {...}和/或其他导出的属性或函数。 有没有什么办法可以将它从string中“编译”成一个对象,这样我就可以使用它了? (另外,我不想像require()那样caching它。)

这是一个使用vm.runInThisContext()简单例子:

 const vm = require('vm'); let code = ` exports['default'] = function() { console.log('hello world'); } ` global.exports = {}; // this is what `exports` in the code will refer to vm.runInThisContext(code); global.exports.default(); // "hello world" 

或者,如果你不想使用全局variables,你可以使用eval来实现类似的function:

 let sandbox = {}; let wrappedCode = `void function(exports) { ${ code } }(sandbox)`; eval(wrappedCode); sandbox.default(); // "hello world" 

这两种方法都假设你提供给它的代码是“安全的”,因为它们都允许运行任意代码。