Node是否运行所需模块中的所有代码?

Does Node run all the code inside required modules?

本文关键字:代码 模块 是否 运行 Node      更新时间:2023-09-26

节点模块是否在需要时运行?

例如:您有一个文件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
})();

一些例子…

'use strict';
var a = 2 * 4;  //this is executed when require called
console.log('required'); //so is this..    
function doSomething() {};  //this is just parsed
module.exports = doSomething;  //this is placed on the exports, but still not executed..

只有在加载时才会运行其他JS代码。

。模块主体中的函数定义将运行并创建一个函数,但该函数不会被调用,直到其他代码实际调用它。

在导出模块外可见的内容之前,如果有相同的代码可以执行它,它将执行,但像类一样导出的内容将在导入它的代码中执行。

例如,如果我有这样的代码

console.log("foo.js")
module.exports = {
     Person: function(){}   
} 

console.log将在您require时执行。