Node.js需要脚本但不运行它

Ale*_*lls 5 require node.js

在Node.js中,当你这样做

var otherscript = require('otherscript');
Run Code Online (Sandbox Code Playgroud)

它根据需要运行脚本

我想知道是否有办法在不运行脚本的情况下"需要"脚本,以便您可以在以后运行它.

有什么理由不是吗?

Anu*_*hne 6

如果您可以编辑“其他脚本”(没有其他人使用该脚本),那么您可以简单地将整个代码包含在一个函数中并将其添加到导出中。例子:

其他脚本:

module.exports = function(){
  //original code goes here
};
Run Code Online (Sandbox Code Playgroud)

然后用作:

var otherscript = require('otherscript');
var obj = otherscript();
Run Code Online (Sandbox Code Playgroud)