Node是否在所需模块中运行所有代码? [英] Does Node run all the code inside required modules?
本文介绍了Node是否在所需模块中运行所有代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
节点模块是否在需要时运行?
Are node modules run when they are required?
例如:您有一个foo.js文件,其中包含一些代码和一些导出.
For example: You have a file foo.js that contains some code and some exports.
当我通过运行以下代码导入文件时
When I import the file by running the following code
var foo = require(./foo.js);
文件foo.js中的所有代码是否都运行并仅在此之后导出?
is all the code inside the file foo.js run and only exported after that?
推荐答案
就像在浏览器的<script>
中一样,只要您需要一个模块,就可以解析并执行代码.
Much like in a browser's <script>
, as soon as you require a module the code is parsed and executed.
但是,取决于模块代码的结构,可能没有函数调用.
However, depending on how the module's code is structured, there may be no function calls.
例如:
// 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
})();
这篇关于Node是否在所需模块中运行所有代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文