We’ve been seeing a lot of articles and guides recently that ask you to install a node module using npm, globally, using
npm install -g <module-name>. Now, we don’t like to preach but there’s a better way and we want you all to know about it.
But first, let’s explain why it’s not a great idea.
Installing a module globally means you have to use that version of the module, globally. This means that all of your projects will end up depending on the same module version; and when you go to update; you’ll screw over at least one other project, probably.
When using nvm, or similar tooling to swap between Node.js versions, every time you switch to a new version of Node, you’ll lose your globally installed modules. This bums you out every time. When I say every time, I mean, every. time.
You’re making a mess of your filesystem. The OCD in us likes to keep our filesystems decently tidy… and diluting that with globally installed node modules sucks.
But back to how we can fix this
It’s quite simple really and it’s two fold but requires you save your node modules as a dev dependencies.
PATHvariable in your
npmscripts. npm scripts automatically add your
./node_modules/.bindirectory into it’s path so that you can address binaries installed via npm automatically. This means you can add the following to your
package.jsonfile and not have to install that module globally.
"foo": "binary-installed-with-npm-module bar"
So there you have it. You don’t need to install your node modules globally any more just to be able to access binaries. Install those modules locally in each project that requires it and you’ll get greater control over what modules you use and which versions you use across different projects.