The default approach I often see is:
// repeat this in all files
var express = require('express');
var mongoose = require('mongoose');
var async = require('async');
...
But in my NodeJS apps I'm doing this:
// include this only on the server file
_express = require('express');
_mongoose = require('mongoose');
_async = require('async');
...
I prefer to use _
prefix to identify libs/modules and I don't use var
because I don't want to repeat the require/setup of all packages on every file of my application.
This way I can require()
modules only one time on server.js file and use it anywhere.
Is this a bad idea?
Modules are cached in nodejs. It is best practice to require where needed.
From the node.js docs:
Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.
Multiple calls to require('foo') may not cause the module code to be executed multiple times. This is an important feature. With it, "partially done" objects can be returned, thus allowing transitive dependencies to be loaded even when they would cause cycles.
In your front-end development (in case it's not just a server-side node question) you could surely make your requires on a base or main js and leave them referenced globally by appending them to the window, the document or any other highly-scoped objects but the best practice would be to require and load modules only when they are needed.