什么被认为是在节点模块内共享"全局"变量的好方法?

ari*_*nai 6 javascript node.js npm node-modules

如何在没有显式相对路径(../../../lib..)的情况下轻松引用模块中的其他目录?

我正在编写节点模块,我想在模块中重用一些全局内容.
最基本的 - 我想将模块的根路径设置为"全局",这样我就可以轻松地调用其他源,而无需使用大量相对路径../../和类似的东西.它可能会导致代码混乱,如果项目结构发生变化,很容易出错或错过它.

所以我在该帖子和其他一些库中看到了很多选项来处理这些事情(例如提供根路径的模块 - app-module-path,rootpath,rfr等)但是它们都引用了基础项目/应用程序,而不是其他人使用的模块.

设置全局是一个坏主意,我理解环境变量也不是一个好主意.

那件事有好的做法吗?也许有一些我没有找到或听说过的东西.

以下是我要避免的内容和我正在寻找的内容的示例:

// avoid things like that:

// ./lib/something/forthat/doit.js
var config = require('../../../config/project/type1/config.js');

// ./config/project/type1/config.js
module.exports = {
  msg: 'hi'
};


// find somethings like that:
// when the root path/require can be found in every location of the module
// and is relative to my app and not the app using my module.

// ./lib/something/forthat/doit.js
var config = require(rootPath + 'config/project/type1/config.js');
// OR
var config = rootRequire('config/project/type1/config.js');
// OR anything else

// ./config/project/type1/config.js
module.exports = {
  msg: 'hi'
};
Run Code Online (Sandbox Code Playgroud)

Amu*_*yap 0

首先......相对路径根本不会造成混乱。相反,您可以称其为混乱(如果您愿意),并且它被认为是最佳实践。但我也能理解你。你不喜欢非常混乱的代码。因此,对于这种情况,您应该将该部分代码作为静态内容提供。因此,您可以通过提供非常登录的尾部路径轻松访问它。但请记住,这种方式是相对路径服务的替代方式。