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?
The require module, which appears to be available on the global scope — no need to require('require') . The module module, which also appears to be available on the global scope — no need to require('module') .
In NodeJS, require() is a built-in function to include external modules that exist in separate files. require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object.
Node. js follows the commonJS module system, and it require to include modules that exist in separate files and for that purpose it has methods like “require” and “ES6 import and export” are available in node.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With