Node.js global require

孤人 提交于 2020-01-13 09:01:13

问题


how can i require a module globally so i can use it in different modules without having to require it again? or do i just have to do that everytime? is there any best practice for this?

heres an example of what i am talking about. lets say i have an index.js like this:

var a = require('a.js'),
utils = require('utils.js');

var str = 'hello this is a test';
str = a.change(str);

utils.return(str);

a.js

var utils = require('utils.js');

exports.change = function(str) {
    str = str.replace('test', 'example');
    utils.return('i changed test to example!');
    return str;
}

utils.js

exports.return = function (msg) {
    console.log(msg);
}

you see i have to require('utils.js') twice, but i would rather require it once in the index.js and have it available in the index.js and a.js as utils. is there any good way to accomplish that?


回答1:


The usual practice in nodejs development is to just require() a module in each module that you need it. The module itself is cached by nodejs so the same module is returned every time and it isn't actually loaded over and over. Doing it this way rather than creating globals generally makes code more modular and reusable since each module uniquely specifies (with require() statements) what it needs rather than having a bunch of modules that depend upon some pre-existing global configuration which creates a lot more dependencies, load order issues, etc...

It is possible to make a single module that does require() on a bunch of other modules and then combines the results into a new master module if that is relevant or useful so other modules only have to require the new master module.

It is not recommended to use globals in place of just using a require() statement. Remember that in nodejs programming, most require() statements are just run at server initialization time and they are cached so there's little reason to avoid the benefits and modularity that using require() instead of globals provides.


I wouldn't personally recommend this because it messes with modularity, but in your specific example, you could also pass the utils module to the a.js constructor:

var utils = require('utils.js');
var a = require('a.js')(utils);


来源:https://stackoverflow.com/questions/31211531/node-js-global-require

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