在处理许多不同的Node.js项目时,我开始使用我想在新的Node.js包中移出的公共代码,以便不多次重写相同的代码。我有一个新的Node.js模块,我在使用npm link
的项目中使用它。
现在,我对如何构建这个公共库以便正确地模块化它感到有点困惑。这就是我现在在我的公共图书馆中所拥有的:
// "my-common-lib"'s app.js
module.exports = {
math: require("./math/mathLib"),
network: require("./network/networkLib")
};
-
//mathLib.js
exports.pi = 3.14;
这有效,我可以在另一个node.js项目中执行以下操作:
var commonLibrary = require("my-common-lib");
var commonMath = commonLibrary.Math;
console.log("Pi: " + commonMath.pi);
虽然这解决了这个问题,但我更喜欢与lodash相似的东西:
var commonMath = require("my-common-lib/math");
console.log("Awesome pi: " + commonMath.pi);
我无法弄清楚lodash是如何做到的,我会definitely like to avoid having a humongous main js file。
TL; DR我想模块化node.js模块,所以我可以要求子模块(require("my-common-lib\myCommonMathLib")
),我该怎么做?
答案 0 :(得分:2)
例如,如果您想使用lodash/array
,则LoDash会有一个array.js
文件,其中包含以下内容:
module.exports = {
'chunk': require('./array/chunk'),
'compact': require('./array/compact'),
因此,您可以在主文件夹中轻松拥有math.js
,其中包含:
module.exports = {
pi: 3.14
// OR
pi: require('./math/pi'); // and have file pi.js inside math folder
}
通过这种方式,您可以将其用作短片:
var math = require('my-common-lib/math');
math.pi; // 3.14
答案 1 :(得分:2)
lodash采用专用模块化构建。例如,查看ES6 build。每个"子项目"有专门的模块,专用的' .js'文件。聚合文件(lodash.js)只是导入所有其他模块。
如果你想要一个好的lib/module
约定,只需在顶层有一个你的lib.js文件(聚合器),在一个目录旁边保留所有内部模块的相同名称。
require("lib")
部分的另一个选项是在"main": "lib.js"
package.json
个配置