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

Vic*_*ava 13 javascript require node.js

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

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

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

var foo = require(./foo.js);
Run Code Online (Sandbox Code Playgroud)

文件foo.js中的所有代码都运行并且只在那之后导出?

tms*_*lnz 10

就像在浏览器中一样,<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
})();
Run Code Online (Sandbox Code Playgroud)

  • 另外,即使在多个地方导入该模块,nodejs 也只运行一次该模块 (2认同)

Kei*_*ith 6

一些例子..

'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..
Run Code Online (Sandbox Code Playgroud)