Last Updated: February 25, 2016
·
602
· fragphace

Require() local files as if they were global

Node.js require() is a wonderful thing but dealing with relative paths like that:

var fooLib = require('../../../../lib/foo');

may be a bit annoying.

You can create a symbolic link in node_modules pointing to the lib directory and then require it in a simpler manner:

var fooLib = require('lib/foo');

All you need is to add postinstall script into your project's package.json:

{
    "scripts": {
        "postinstall": "ln -sf ../lib node_modules/;"
    }
}

Script will automatically create symlinks on npm install. If for some reason links weren't created you could always generate them by running postinstall script by hand:

npm run-script postinstall