简体   繁体   English

Nodejs代码重用最佳实践

[英]Nodejs Code Reusing Best Practices

I am new to nodejs. 我是nodejs的新手。 I can't get my mind over organizing module code reusing in Nodejs. 我无法在Nodejs中组织模块代码重用。 For example : 例如 :

Let's say I have 3 files, which corresponds to 3 library files I wish to load. 假设我有3个文件,对应于我希望加载的3个库文件。 Then, I have 5 files which requires the 3 libraries. 然后,我有5个文件,需要3个库。

Will I have to repeat typing the following in the 5 files? 我需要在5个文件中重复输入以下内容吗?

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? 我有什么办法可以在5个文件中自动包括这3行代码(可能不止3行)?

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: 但是,如果您愿意,可以很容易地将所有3个库包装到一个整体模块中:

//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'); 然后用var monolith = require('./monolith');加载它var monolith = require('./monolith');

Yes, you can require a folder as a module. 是的,您可以将文件夹作为模块。 If you want to require() a folder called ./test/. 如果您需要require()一个名为./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. 在./test/内部,在./lib/目录中创建具有文件夹名称的package.json文件和具有相同名称的主javascript文件。

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

Now you can use require('./test') to load ./test/lib/test.js. 现在您可以使用require('./ test')加载./test/lib/test.js。 similarly you can require other files 同样,您可以要求其他文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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