javascript - Node 是否在所需模块中运行所有代码?

标签 javascript node.js require

Node 模块是否在需要时运行?

例如:您有一个文件 foo.js,其中包含一些代码和一些导出。

当我通过运行以下代码导入文件时

var foo = require(./foo.js);

文件 foo.js 中的所有代码是否都运行并仅在此之后导出?

最佳答案

很像浏览器的<script> ,只要你需要一个模块,代码就会被解析并执行。

但是,根据模块代码的结构,可能没有函数调用。

例如:

// my-module-1.js
// This one only defines a function.
// Nothing happens until you call it.
function doSomething () {
    // body
}
module.exports = doSomething;


// my-module-2.js
// This one will actually call the anonymous
// function as soon as you `require` it.
(function () {
    // body
})();

关于javascript - Node 是否在所需模块中运行所有代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40464552/

相关文章:

node.js - 在 node.js 中 require 如何与 new 运算符一起工作?

javascript - react native : require() with Dynamic String?

ruby-on-rails - 是否可以在单独的 require 语句中包含 Rails actionpack?

javascript - Meteor JS - 添加新帖子时 $sort 不起作用

node.js - 有没有办法在node js中设置文件属性

node.js - 如何在没有 Yeoman 的情况下创建 npm 项目生成器

node.js - ffmpeg x11grab 导出视频 16 :9 is distorded

javascript - 如何处理加载 iframe 时的错误?

javascript - JQuery 生成同级元素,然后一次性追加所有元素

javascript - 如何递归地将数组中的每n个元素传递到函数中