简体   繁体   English

Node.js单独的模块依赖性

[英]Node.js separate module dependencies

What is the best way to separate all module dependencies into a new file called dependencies.js , and requiring that file in for example server.js . 将所有模块依赖项分离到一个新文件中的最佳方法是什么,该文件名为dependencies.js ,并在例如server.js要求该文件。 How do i return all these requires? 我如何退回所有这些要求?

var express = require('express')
  , stylus = require('stylus')
  , fs = require('fs')
  , https = require('https')
  , app = express();

You would need to assign them to the global object, so you shouldn't do it at all 您需要将它们分配给global对象,因此您根本不需要这样做

global.express = require('express');
global.stylus = require('stylus');
global.fs = require('fs')
global.https = require('https')
global.app = global.express();

There are actually a lot of reasons not to do this, but I'll boil it down. 实际上,有很多理由不这样做,但是我将其归结为简单。 First, you know that when declaring a variable in a module (eg var Foo = require('foo') ), that variable is a part of the local scope of that module. 首先,您知道在模块中声明变量时(例如var Foo = require('foo') ),该变量是该模块局部作用域的一部分。 global on the other hand is global to all of the modules. global ,另一方面是全球所有模块。 Think about the implications of all your modules sharing the same namespace for critical things which can not be guaranteed to be in any one state at a particular point in run-time ( global is actually reset whenever node decides it needs to be!). 考虑一下所有模块为关键事件共享同一名称空间的含义, 这些关键事件不能保证在运行时的特定时刻处于任何一种状态(实际上,只要节点决定需要global就会重置!)。 This problem is potentially exacerbated if you ever begin using multiple processes (as @Hippo mentioned but did not explain). 如果您开始使用多个进程(如@Hippo提到但未解释),则此问题可能会加剧。

I can see why this would seem like a good idea at first, but the tiny amount of DRY you'd get from this technique pales in comparison to the unexpected failures you'd be hiding in your code. 我可以理解为什么一开始这似乎是个好主意,但是与隐藏在代码中的意外失败相比,您从这种技术中获得的少量DRY显得苍白。

IMO, it's much better to explicitly declare your dependencies in each module anyway. IMO,最好还是在每个模块中显式声明您的依赖项。 Sharing a list of deps across all modules would obfuscate the logical structure of your program. 在所有模块之间共享deps列表将混淆程序的逻辑结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM