Javascript“require()”方法

在python中,当你导入一个模块时,导入模块的'if name == main '块内部的语句不会被执行。

有没有什么等效的方法可以防止在JavaScript中导入的模块中执行不需要的语句?

通过fuyushimoya的评论。

当一个文件直接从Node运行时,require.main被设置为它的模块。 这意味着您可以确定文件是否已经通过testing直接运行

require.main === module 

对于文件foo.js,如果通过节点foo.js运行,则为true;如果运行require('./ foo'),则为false。

– Node.js文档

所以:

 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 } 

简单地将你的语句分组在函数中,然后导出你想要的函数。

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

更多的在这里 。