javascript - 为 node.js 中 module.exports 的所有方法导入模块
问题描述
我有一个要导出的 node.js 模块,其中包含多个功能。其中许多功能需要一个通用模块,如下面的代码所示:
module.exports = {
a: function () {
const util = require("commonModule");
// Do things
},
b: function () {
const util = require("commonModule");
// Do other things
},
c: function () {
const util = require("commonModule");
// Do more other things
}
}
如果我在 module.exports 格式中没有这个,我可以简单地执行以下操作并导入模块一次,它将可用于所有功能:
const util = require("commonModule");
function a(){
// Do things using commonModule
}
function b(){
// Do other things using commonModule
}
有没有办法修改 module.exports 版本,这样当用户导入我的模块时,它会自动导入 commonModule 并为所有函数提供它,而不是让每个函数调用导入一个新的 commonModule 实例?
解决方案
您不需要在每个单独的函数中都需要它。你可以简单地这样做:
const util = require("commonModule");
module.exports = {
a: function () {
// Do things
},
b: function () {
// Do other things
},
c: function () {
// Do more other things
}
}
或者如果你愿意,这个:
const util = require("commonModule");
function a(){
// Do things using commonModule
}
function b(){
// Do other things using commonModule
}
module.exports.a = a;
module.exports.b = b;
甚至第三种方式:
const util = require("commonModule");
module.exports.a = function (){
// Do things using commonModule
}
module.exports.b = function () {
// Do other things using commonModule
}
你选择哪一个取决于你。
推荐阅读
- amazon-web-services - 每个区域的 Cognito 池与每个租户的 Cognito 池
- python-3.x - RGB 转 HSV 与 BGR 转 HSV 一样吗?
- javascript - 在 Javascript 上比较并获取对象的一些值数组
- reactjs - 如何将列表“键”值作为嵌套组件中的道具传递?
- python - 使用curve_fit拟合列表中2个变量的数据
- vue.js - 创建一个简单的 VUE.JS 应用程序
- ios - 使用 UIViewPropertyAnimator 同步动画 CALayer 属性和 UIView
- sql - PLS-00103:遇到符号“SELECT”pl/sql 错误
- python - (Tkinter) 为什么 itemconfig 不改变我的对象的颜色?
- reactjs - 把所有东西都变成一个组件有什么害处吗?