I have the following application structure:
application
|- config
|----- config.js
|- routes
|------ api
|-----------router.js
|- Application.js
|- package.json
In /routes/api/router.js module I need to require /config/config.js file and do the following:
require('../../config/config.js');
I found the code above ugly and want to make it more pretty. Also if I move /routes/api/router.js
to another folder I have to refactor all requires. What is the best practices to require that modules and is it possible to require config.js from application folder root, something like the following:
require('/config/config.js');
Thanks.
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.
No, You don't need to push your node_modules folder to production whether it is a static export or dynamic build. When you export a static build the source file is converted into HTML & js files. So there is no need for node modules on production env.
Node will look for your modules in special folders named node_modules . A node_modules folder can be on the same level as the current file, or higher up in the directory chain. Node will walk up the directory chain, looking through each node_modules until it finds the module you tried to load.
There are a few ways to get around this problem. One is to put all your shared code (like config.js
) in a directory under node_modules
(using lib
here in case you want to have directories other than config
in there):
application
|- node_modules
|----- lib
|---------- config
|-------------- config.js
|- routes
|------ api
|-----------router.js
|- Application.js
|- package.json
So then you could require config.js using require( 'lib/config/config.js' )
.
Alternatively, you could create a lib
symlink in node_modules
and link it to lib in your application directory structure:
application
|- node_modules
|----- lib -> ../../lib
|- lib
|------ config
|---------- config.js
|- routes
|------ api
|-----------router.js
|- Application.js
|- package.json
One other alternative, which unfortunately is discouraged by the node docs, is to use NODE_PATH
which lets you specify directories that node's require()
algorithm should look into. Following the same pattern as above with lib
, you would do:
application
|- lib
|------ config
|---------- config.js
|- routes
|------ api
|-----------router.js
|- Application.js
|- package.json
and set NODE_PATH
equal to $path_to_application/lib
.
UPDATE
Found this great discussion on the topic which includes the options above as well as a few other ones.
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