Require() 从字符串到对象

Require() from string into object

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

这是一个使用 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"

或者,如果您不想使用全局变量,您可以使用 eval:

实现类似的效果
let sandbox     = {};
let wrappedCode = `void function(exports) { ${ code } }(sandbox)`;

eval(wrappedCode);

sandbox.default(); // "hello world"

这两种方法都假设您输入的代码是 "safe",因为它们都允许 运行 任意代码。