Last active
August 29, 2015 14:06
-
-
Save v0lkan/da63a03dbc5aebd26d5c to your computer and use it in GitHub Desktop.
#nodejs #tip Tame your dependencies with a `rekuire` function ;)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ---------------------------------------------------------------------------- | |
// 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'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks @6Bangs for suggesting unix-like /path/foo/bar versus path/foo/bar semantics; allowing me to get rid of the boolean.