Javascript 'require()' 方法

Javascript 'require()' method

在python中,当你导入一个模块时,里面的语句 'if name == main'导入模块的块没有执行。

是否有任何等效方法可以防止在 javascript 中导入的模块中执行不需要的语句?

只需将您的语句分组到函数中,然后导出您想要的函数。

exports.function1 = new function () {
  //some code
}
function function2() {
  //some other code 
}

更多内容here

来自 fuyushimoya 的评论。

When a file is run directly from Node, require.main is set to its module. That means that you can determine whether a file has been run directly by testing

require.main === module

For a file foo.js, this will be true if run via node foo.js, but false if run by require('./foo').

Node.js documentation

所以:

if (require.main === module) {
    // Code that runs only if the module is executed directly
} else {
    // Code that runs only if the code is loaded as a module
}