Javascript'要求()'方法

时间:2015-07-05 09:51:47

标签: javascript node.js require

在python中,当你导入一个模块时,里面的语句 '如果名称== 主要'不执行导入模块的块。

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

2 个答案:

答案 0 :(得分:5)

通过fuyushimoya的评论。

  

直接从Node运行文件时,require.main设置为它   模块。这意味着您可以确定文件是否已运行   直接通过测试

require.main === module
     

对于文件foo.js,如果通过节点foo.js运行,则为true,但为false   如果由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
}

答案 1 :(得分:-2)

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

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

更多信息here