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;
var
)Use magic global variables, without var
.
Example:
fs = require("fs");
instead of
var fs = require("fs");
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.
global.yourVariable = ...
Fields attached to global
object become global variables that can be accessed from anywhere in your application.
So, you can do:
global.fs = require("fs");
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 the global_modules.js
file.
In server.js
you will do this:
require("./global_modules");
and in global_modules.js
you will have:
_modules = {
account_controller: require('/account/controller.js'),
account_middleware: require('/account/middleware.js'),
products_controller: require('/products/controller.js'),
...
}
or
global._modules = {...}
In server.js
you will be able to do:
_modules.account_controller // returns require('/account/controller.js'),
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With