Require() 从字符串到对象

alp*_*ogg 1 require node.js

假设我有一个字符串中的js文件的内容。此外,假设它具有exports['default'] = function() {...}和/或其他导出的属性或函数。有什么方法可以将该字符串“要求”(将其编译)为对象,以便我可以使用它?(另外,我不想像require()以前那样缓存它。)

rob*_*lep 5

这是一个非常简单的例子,使用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"
Run Code Online (Sandbox Code Playgroud)

或者,如果您不想使用全局变量,您可以使用以下方法实现类似的效果eval

let sandbox     = {};
let wrappedCode = `void function(exports) { ${ code } }(sandbox)`;

eval(wrappedCode);

sandbox.default(); // "hello world"
Run Code Online (Sandbox Code Playgroud)

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