Recent node docs say that modifying require.paths
is bad practice. What should I do instead?
You can now start using modern ES Import/Export statements in your Node apps without the need for a tool such as Babel. As always, if you have any questions, feel free to leave a comment.
One of the major differences between require() and import() is that require() can be called from anywhere inside the program whereas import() cannot be called conditionally, it always runs at the beginning of the file. To use the require() statement, a module must be saved with . js extension as opposed to .
Node. js follows the CommonJS module system, and the built-in require function is the easiest way to include modules that exist in separate files. The basic functionality of require is that it reads a JavaScript file, executes the file, and then proceeds to return the exports object.
A module loader called RequireJS exists for in-browser use without the use of Node. js or Rhino. The data-main attribute will point to your main script where you can load the rest of your scripts using: require(["helper/util"], function(util) { //This function is called when scripts/helper/util.
I believe the concern is that it can be repeatedly modified at run time, rather than just set. That could obviously be confusing and causes some quite bizarre bugs. Also, if individual packages modify the path the results are applied globally, which is really bad and goes against the modular nature of node.
If you have several library paths of your own, the best solution is to set the NODE_PATH environment variable before launching node. Node then picks this up when it's launched and applies it automatically.
I keep the related models in the same dir or a sub dir and load using:
var x = require('./mod/x');
In case it's an external module, I install it using npm that puts the module correctly in NODE_PATH.
I've never changed require.paths.
have a look at https://github.com/patrick-steele-idem/app-module-path-node; you can add a directory to the require
statements in the top level, without influencing the paths of sub-modules.
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