在 python 中,当你导入一个模块时,里面的语句 导入模块的“if name == main” block 未执行。
是否有任何等效的方法可以防止在 javascript 的导入模块中执行不需要的语句?
最佳答案
通过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').
所以:
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
}
关于Javascript 'require()' 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31229090/