Last Updated: February 25, 2016
·
876
· 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

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside