Javascript'require()'方法

shi*_*ocv 1 javascript require node.js

在python中,当您导入模块时,不会执行导入模块的"if name == main "块中的语句.

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

Que*_*tin 5

通过fuyushimoya的评论.

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

require.main === module
Run Code Online (Sandbox Code Playgroud)

对于文件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
}
Run Code Online (Sandbox Code Playgroud)