groot
v1.0.0
Published
Module loader with global variables
Downloads
6
Maintainers
Readme
groot
Module loader with global variables
This module tries to solve and improve the module loading. It's very common to have require()
's with relative paths like ../../../foo/bar
.
This is a well-known problem known by the Node.js community: Better local require() paths for Node.js. There are some solutions that seem to work but I personally dislike most of them, especially the one which uses the node_modules
directory to store the modules of your app. My advice is to only use node_modules
for external modules, never for storing you own modules.
The way this module avoids the relative paths is by using global variables. This is by far the best solution to this problem; clean, easy to understand and compatible with all the operating systems.
require('groot')({ requireVar: '__require', rootVar: '__root' });
If you execute the above piece of code in the main file, which is typically stored in the root directory, __root
and __require
will be set as global variables. __root
will contain the absolute path of the root directory, and __require
will be a function similar to require()
but for loading the modules relative to the root directory.
By default, the root directory is the fiel's __dirname
of the caller.
For example, given the project directory tree:
.
├─ app.js
├─ foo
│ └─ bar.js
└─ baz
└─ qux.js
// app.js
require('groot')({ requireVar: '__require', rootVar: '__root' });
// bar.js
var qux = __require('./baz/qux');
// "." points to the __dirname of app.js, that is, the project's root directory
Note that __require('baz/qux')
(without a dot .
) is intentionally invalid and will throw an error for avoiding confusion with modules stored inside node_modules
. The path must begin with a dot, .
.
An extra option can be specified to manually set the root directory:
require('groot')({
requireVar: '__require',
rootVar: '__root',
rootDir: __dirname
});
By setting rootDir
to __dirname
, this is, in fact, the same as not setting the rootDir
option.
module([options]) : undefined
Options:
- requireVar - String
Name of the global variable to require modules. - rootVar - String
Name of the global variable of the root directory. - rootDir - String
Absolute path that will be used as the root directory.