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/