Node是否运行所需模块中的所有代码?
Does Node run all the code inside required modules?
节点模块是否在需要时运行?
例如:您有一个文件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
时执行。
相关文章:
- Webpack通过npm将代码拆分为单独的模块,以及如何编译es6
- TypeScript代码类似于揭示模块模式结构
- 模块化&重用使用ExtJS编写的代码
- 找不到模块 './build/Release/bson'] 代码: 'MODULE_NOT_FOUND' } js-bs
- 将JavaScript代码迁移到具有String.prototype扩展名的node.js模块
- 如何在nodejs中模块化代码
- 类代码结构,使用非立即执行的模块模式变体
- 为什么这段代码会导致使用phantom模块的Node.js挂起
- 使用解析云代码模块通过 SendGrid 发送附件
- 我如何实例化不同页面上的 require.js 模块,带有代码点火器的部分
- 如何在 joomla 模块管理中添加 php 代码
- 浏览器化只执行一次模块代码,在多个需要调用上
- 如何在 YUI 模块中运行代码
- 是否可以包含许多.js文件以使我的代码看起来模块化
- RequireJS:如何处理浏览器和服务器之间共享的代码的不同模块依赖关系
- 如何在模块中测试 OpenCV nodejs 绑定代码
- WebStorm JSDoc 类声明,用于使用 node.js 模块完成代码
- 条带云代码模块 Parse.com 的限制
- 如何从Parse.com云代码模块返回响应
- 如何从云代码模块返回Parse承诺