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
. 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.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 (e.g. var Foo = require('foo')
), that variable is a part of the local scope of that module. global
on the other hand is global to all of the modules. 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!). This problem is potentially exacerbated if you ever begin using multiple processes (as @Hippo mentioned but did not explain).
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.
IMO, it's much better to explicitly declare your dependencies in each module anyway. Sharing a list of deps across all modules would obfuscate the logical structure of your program.