【问题标题】:Import module for all methods of module.exports in node.js为 node.js 中 module.exports 的所有方法导入模块
【发布时间】:2020-07-15 13:05:00
【问题描述】:

我有一个我想要导出 的 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 实例?

【问题讨论】:

    标签: javascript node.js module node-modules


    【解决方案1】:

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

    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
    }
    
    

    你选择哪一个取决于你。

    【讨论】:

    • 如果我的回答对您有帮助,请务必接受,以便其他人知道您的问题已解决。
    • 我知道,只是我只能在问题出现 10 分钟后才能接受,所以我会尽快接受。你太快了;D
    猜你喜欢
    • 2020-09-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-22
    • 2016-10-25
    • 2011-10-31
    • 1970-01-01
    相关资源
    最近更新 更多