首页 > 解决方案 > 为 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 实例?

标签: javascriptnode.jsmodulenode-modules

解决方案


您不需要在每个单独的函数中都需要它。你可以简单地这样做:

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
}

你选择哪一个取决于你。


推荐阅读