Skip to content

Instantly share code, notes, and snippets.

@v0lkan
Last active August 29, 2015 14:06
Show Gist options
  • Save v0lkan/da63a03dbc5aebd26d5c to your computer and use it in GitHub Desktop.
Save v0lkan/da63a03dbc5aebd26d5c to your computer and use it in GitHub Desktop.
#nodejs #tip Tame your dependencies with a `rekuire` function ;)
// ----------------------------------------------------------------------------
// File: PROJECT_ROOT/ ... / servers/app1/app.js
// Define this **before** all the `require`s.
function initRekuire(baseDir, appDir) {
var base = baseDir || '.',
app == appDir || '.';
global.rekuire = function(name) {
return require(
path.join(
__dirname,
name[0] === '/' ? base : app
)
);
};
}
// Project root is 2 levels above, app rekuires are relative
// to the current dir that the node process is running at.
initRekuire('../..', '.');
var stuff1 = require('stuff1');
stuff2 = require('stuff2');
// ----------------------------------------------------------------------------
// File: PROJECT_ROOT/servers/app1/foo/bar/baz/blah.js
// Now to require "PROJECT_ROOT/bazinga.js"; instead of this...
require('../../../../bazinga');
// You can use this:
rekuire('/bazinga');
// And to require "PROJECT_ROOT/servers/app1/nanana/batman.js"
// Instead of this
require('../../../nanana/batman');
// You can use this:
rekuire('nanana/batman');
@v0lkan
Copy link
Author

v0lkan commented Sep 6, 2014

Thanks @6Bangs for suggesting unix-like /path/foo/bar versus path/foo/bar semantics; allowing me to get rid of the boolean.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment