I want to create one global module file, and then have all my files require that global module file. Inside that file, I would load all the modules once and export a dictionary of loaded modules.
How can I do that?
I actually tried creating this file...and every time I require('global_modules')
, all the modules kept reloading. It's O(n).
I want the file to be something like this (but it doesn't work):
//global_modules.js - only load these one time
var modules = {
account_controller: '/account/controller.js',
account_middleware: '/account/middleware.js',
products_controller: '/products/controller.js',
...
}
exports.modules = modules;
1. Using a magic variable (declared without
var
)Use magic global variables, without
var
.Example:
instead of
If you don't put
var
when declaring the variable, the variable will be a magic global one.I do not recommend this. Especially, if you are in the strict mode (
"use strict"
) that's not going to work at all.2. Using
global.yourVariable = ...
Fields attached to
global
object become global variables that can be accessed from anywhere in your application.So, you can do:
This is not that bad like 1., but still avoid it when possible.
For your example:
Let's say you have two files:
server.js
(the main file) and theglobal_modules.js
file.In
server.js
you will do this:and in
global_modules.js
you will have:or
In
server.js
you will be able to do:require
already does it. Try loading a module, modify it and then load it another time in another place or file: