Javascript 'require()' 方法

标签 javascript node.js require

在 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').

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
}

关于Javascript 'require()' 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31229090/

相关文章:

javascript - 如何获取集合中每个发件人的最新消息?

javascript - Angular 5-如何向构造函数添加多个参数?

javascript - 使用 Object.assign() 删除对象属性

javascript - NodeJS 提示如果在 if 语句中设置了某个对象,则该对象是未定义的

javascript - URL 不是 Node.js 的函数

javascript - 如何正确从 firebase 检索数据?

javascript - Soundcloud 如何从专辑封面创建背景渐变?

javascript - 我如何使用 'gulp-babel' throw ERROR 不要停止 Node 服务器

node.js - 我应该如何从 node_modules 文件夹外部有效地要求模块?

PHP require_once 没有得到一个变量