延迟加载Nodejs中的模块 [英] Lazy loading of modules in Nodejs
问题描述
我的第一个问题是:谁负责处理Nodejs应用程序中的 require
语句?是Node本身吗?还是CommonJS?还是RequireJS? Node中包含CommonJS吗?那RequireJS呢?
My first question is : Who is responsible to handle require
statements in a Nodejs application ? is it Node itself ? or CommonJS ? or RequireJS ? Is CommonJS included in Node ? what about RequireJS?
现在我的第二个问题:
我有一条if-else语句,该语句确定我们是否渲染服务器端或客户端。我想在客户端或服务器端进行渲染时加载不同的库。是否可以在运行时加载模块?
I have an if-else statement , which decides if we are rendering on server side or client side. I want to load different libraries when it's rendering on client side or server side. Is it possible to load the modules in runtime ? exactly at the moment it's required ?
if (typeof window === undefined){
var serverSideLibrary = require('A');
//....
}else{
var clientSideLibrary = require('B');
}
看起来Node在启动应用程序之前已加载了所有必需的内容。因此,是否需要在代码顶部或if-else块中使用它并不重要。
It looks like Node loads everything required before starting the application. So it's not important if you require it at the top of the code or in that if-else block.
推荐答案
在Node中。 js,Node本身处理要求
。而且您错了—在程序的评估达到要求之前,不会评估要求
。如果您有此代码:
In Node.js, Node itself handles require
. And you're mistaken—a require
is not evaluated until the program's evaluation reaches it. If you have this code:
var mod;
setInterval(function() {
if (true) {
mod = require("a");
} else {
mod = require("b");
}
}, 5000);
...您可以确定两件事:1.模块 b
将永远不会被加载,并且2.模块 a
不会被加载,直到经过五秒钟。
...you can be sure of two things: 1. Module b
will never be loaded, and 2. Module a
won't be loaded until five seconds have elapsed.
在浏览器中,仅当您使用定义需求的库(例如RequireJS,Browserify或Webpack)时定义需求
。通常,这些工具与Node的行为保持紧密联系:尽管浏览器可能会一次下载所有代码(尤其是如果您有一个将所有模块放入一个文件的构建步骤),它们会将每个模块包装在一个函数中,因此直到它被要求
d。
In the browser, require
is only defined if you use a library that defines it, like RequireJS, Browserify or Webpack. In general these tools stay close to Node's behavior: While the browser might download all of the code at once (especially if you have a build step that puts all of your modules into a single file), they will wrap each module in a function so that it won't actually be evaluated until it's require
d.
如果您要加载不同的模块取决于无论您的代码是在客户端还是服务器上运行,我都建议您在构建步骤中执行此操作-大多数构建工具(如上面提到的那些工具)都具有此功能或可以作为插件使用-而不是仅 if
语句,因为使用 if
语句,您仍在使浏览器下载代码永远不会使用。
If you want to load different modules depending on whether your code is running on the client or the server, I would recommend doing this in your build step—most build tools, like those mentioned above, have this functionality or it's available as a plugin—instead of just an if
statement, because with the if
statement you're still making the browser download code it's never going to use.
这篇关于延迟加载Nodejs中的模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!