在 node/express 中,有没有办法将依赖项声明分离到它自己的文件中?

Is there a way to separate dependency declarations into a file of it's own in node/express?

我正在学习 node.js、express 等,我的代码有点混乱。我想要做的是获取我所有的依赖声明,例如:

var mongoose = require('mongoose');
var express = require('express');
var path = require('path');
etc, etc, etc

并将它们放在自己的单独模块中,然后在我的主 app.js 的顶部,只需执行以下操作:

require('./modules/variables.js');

这样的事情有可能吗?我已经研究了很多,但老实说,我什至不确定要寻找什么。任何建议将不胜感激!!

可能不是最好的方法,但我想你可以创建一个模块来导入所有这些依赖项,并将它们粘贴到上下文变量中,如下所示:

export dependencies = {
  mongoose : require('mongoose'),
  path : require('path'),
  ... etc
};

然后要求在每一页的顶部:

var dependencies = require('./[<path to your module>]/dependencies');

然后通过从依赖项对象中推迟来引用那些依赖项:

dependencies.mongoose.somefunction ....

您可以创建一个单独的文件(比方说 variables.js

module.exports = {
    myFirstVar: 1234,
    mySecondVar: 'Hi there!'
};

然后你可以使用

来要求你的变量
var myVariables = require('path/variables.js')

console.log(myVariables.myFirstVar) //1234

如果您真的想这样做,您可以在代码的早期执行以下操作:

global.mongoose = require('mongoose');
global.express = require('express');
global.path = require('path');

有些人会认为这是异端或非常糟糕的编程。就个人而言,我发现它比在许多文件的顶部有相同的一组 require 行更难看。

例如,我们在每个文件中使用 log4js,并且 log4js 变量始终是 log4js 模块本身,所以我认为在其中包含一行 global.log4js = require('log4js'); 是可以接受的与在每个文件中都有行 var log4js = require('log4js'); 相比,这是一个中心位置。

你也写了

I have trouble getting the variables from my main app.js to carry over to the exampleModule.js

global 的诀窍是 而不是 实现该目标的方法。如果您在不同的地方需要变量或数据,您应该在有 variable/data 的地方使用 export,在需要它们的地方使用 require

例如,在app.js中:

// db is the mongoose connection
module.exports = {
    db: db
};

并且在 exampleModule.js 中:

var appVars = require('./app.js');
// Now you can do something with appVars.db

(注意:这不是最好的命名方式。)