Node: requiring module inside function?

人盡茶涼 提交于 2021-02-08 12:22:19

问题


I was browsing the source code for a command line utility in Node, and saw the following code.

function help() {
    var colors = require('colors');
    var package = require('../package');
    ....
    ....
}

I had not seen require being used inside a function in this way before. I always assumed it was best practice to include it at the top of the file. This is the entry file for this program, and this function is only called in a specific case--but those packages are used elsewhere in the program. When I asked the author of the code for his reasoning, he simply stated that he "didn't want to import all the libraries at once."

Is this good/bad practice? Are there significant implications to load-up time by not requiring these packages at the top of the module, and instead only when these functions are invoked?


回答1:


UPDATE: I think a better answer is here: Lazy loading in node.js

MY INITIAL COMMENTS: Well it's a matter of practice, some guys like it at the top while some like lazy-loading. In my opinion both are good, and should be used as per need, so I think that author is right here, because loading a whole bunch libraries at the startup would overload the module with much of the stuff that is never used, and hence would increase the load-time. And although loading the libraries on demand is a synchronous operation, but if we look help method as an entity, then it would give an asynchronous module loading effect (see AMD, which is a popular pattern).

Lazy loading is also a good selection if you have to make a choice between which libraries to load in a particular case, like for example

var isOSX;
// some code here which finds if this is OSX
// then this
if (isOSX === true) {
  var platformHelper = require('supercoolosxhelper');
} else {
  var platformHelper = require('yetanothercoolhelper');
}

In short, you should anticipate in your code if the probability of using a method is high or even mid, then you should require at the top, otherwise if it's low then it would be nice if the module is required on need basis.




回答2:


In the case of Node, it really comes down to mostly a style choice.

Loading a module from disk takes hardly any time at all, so there really isn't anything there in terms of performance gain. Some folks like to keep modules as close to the point where they will be used, that's all.

Now, client side, its all different and is heavily based upon your package manager.



来源:https://stackoverflow.com/questions/35817080/node-requiring-module-inside-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!