Node 运行 是否包含所需模块中的所有代码?
Does Node run all the code inside required modules?
节点模块 运行 何时需要?
例如:您有一个文件 foo.js,其中包含一些代码和一些导出。
当我通过运行以下代码导入文件时
var foo = require(./foo.js);
文件中的所有代码都是foo.js 运行,然后才导出?
仅在任何其他 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..
在导出模块外部可见的内容之前,如果有相同的代码可以执行它,它会执行,但是像 class 一样导出的内容将在导入的代码中执行它。
例如,如果我有这个代码
console.log("foo.js")
module.exports = {
Person: function(){}
}
console.log
将在您 require
时执行。
节点模块 运行 何时需要?
例如:您有一个文件 foo.js,其中包含一些代码和一些导出。
当我通过运行以下代码导入文件时
var foo = require(./foo.js);
文件中的所有代码都是foo.js 运行,然后才导出?
仅在任何其他 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..
在导出模块外部可见的内容之前,如果有相同的代码可以执行它,它会执行,但是像 class 一样导出的内容将在导入的代码中执行它。
例如,如果我有这个代码
console.log("foo.js")
module.exports = {
Person: function(){}
}
console.log
将在您 require
时执行。