简体   繁体   中英

Nodejs Code Reusing Best Practices

I am new to nodejs. I can't get my mind over organizing module code reusing in Nodejs. For example :

Let's say I have 3 files, which corresponds to 3 library files I wish to load. Then, I have 5 files which requires the 3 libraries.

Will I have to repeat typing the following in the 5 files?

require("./library-1.js");
require("./library-2.js");
require("./library-3.js");

Is there any way for me to automatically include these 3 lines of code (which is potentially more than just 3) in the 5 files?

Generally yes you end up with this kind of repetition, but the explicit dependencies are really helpful next year when you go to refactor your app. However, You can very easily wrap all 3 libraries into a monolithic module if you prefer:

//monolith.js
exports.lib1 = require('./library-1');
exports.lib2 = require('./library-2');
exports.lib3 = require('./library-3');

Then just load that with var monolith = require('./monolith');

Yes, you can require a folder as a module. If you want to require() a folder called ./test/.

Inside ./test/, create a package.json file with the name of the folder and a main javascript file with the same name, inside a ./lib/ directory.

{
  "name" : "test",
  "main" : "./lib/test.js"
}

Now you can use require('./test') to load ./test/lib/test.js. similarly you can require other files

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM