模块化模块?需要父模块中的部分

Modular Module? Require parts of module in parent

本文关键字:模块 模块化      更新时间:2023-09-26

编写一个节点.js模块,并希望尝试分解我的代码/保持整洁。

从本质上讲,我想要的是为模块的每个部分(身份验证、用户等)提供一个单独的文件/文件夹,并要求它们都来自父包,然后父包将被公开。

例如,文件结构为:

index.js
auth.js
users.js

index.js内部,有:

module.exports = {
    some_variable : 1,
    authentication_variable : '',
    auth : require('./auth'),
    users : require('./users')
}

然后,我希望some_variable可以从每个包中访问,并且users能够引用auth,反之亦然,并通过auth设置authentication_variable

从本质上讲,我希望它们在一个类中,但由于它将在 Express 应用程序中的多个路由中使用,我希望它保留主文件中需要时的变量/状态。

如果我将其全部保存在同一个文件中,我可以做到这一点,但不太确定如何做到这一点,因为当我需要该文件时,它无法访问其父级的范围。

到目前为止,作为MWE,我所拥有的:

module.exports = x = {
    globals : {
        id : 123456
    },
    auth : {
        setId : function(id){
            x.globals.id = id;
        },
        getAuthToken : function(){
            return x.globals.id;
        }
    },
    users : {
        doThing : function(name, id){
            x.auth.setId(id);
            console.log(x.auth.getAuthToken === id); // true
        }
    }
}

我已经尝试了下面的建议,但它不起作用。 我不能在另一个模块中拥有仍然可以访问最大范围的子函数。

理想情况下,我想要一种方法,全部放在一个包里,test-package

index.js
module.exports = {
    test : function(){
        console.log(this); // shows this entire object {test : function, auth: function}
    },
    auth : require('./auth')
}
auth.js
module.exports = {
    check : function(){
        console.log(this); // shows {test : function, auth : function}
    }
}

然后,在一个单独的项目中

var my_mod = require('test-package');
my_mod.test(); // shows as before
my_mod.auth.check(); // shows same

如果这是不可能的,至少有一种从auth.js内部访问整个index.js模块的方法。

您可以使用

this关键字:

索引.js

require('./module').auth();

模块.js

module.exports = {
  some_var: 1,
  auth: require('./auth'),
  user: require('./user')
}

身份验证.js

module.exports = function() {
  console.log(this);
  this.some_var = 10;
  this.user();
}

用户.js

module.exports = function() {
  console.log(this);
}