How often have you seen instructions for installing a project that are something like this?
git clone https://wherever/the/project/is
npm install -g gulp # <-- 😱
(or, instead of gulp, any other utility that the project requires for development)
This is not a good idea. You’re installing the same version of a utility globally, and perhaps the project has not been tested with that version. Things might break or even worse, work not-so-well in a strange, undebuggable way!
Don’t do it.
A better way is to use npm scripts, which belong to the project, and specify development dependencies in package.json, so when you run npm install, it also installs devDependencies locally to the projects’ node_modules folder. This keeps everything under control and does not pollute other people’s computers global space.
So, for example, if a project was asking users to run npm install -g gulp, they should do this instead:
- Install gulp locally as a development dependency, saving it to package.json:
npm install --save-dev gulp
- Add a new entry to the scripts array in package.json:
- Ask users to run
the first time. And
npm run build
each time they need to build the project
The reason this works is because when npm runs a script, it modifies the current PATH variable to add node_modules/.bin, which contains any binaries that you installed as part of your modules. So your computer will search for binaries starting in the .bin folder, before searching in any other default location for binaries in your computer (e.g. /usr/bin)
You can find more documentation about this behaviour in the run-script page of the npm manual. I really encourage you to read it as it has lots of good stuff and Things You Wished Had Known Before 🙂
And in case it makes things clearer, this is how a hypothetical package.json would look before:
With this, the devDependency is clearly stated on the package.json file, the project developer will be developing with that version, and will not get surprises! (and the users of the module won’t either).
Another advantage of this approach is that you are not tying the project to a specific utility.
If you decide to use grunt instead of gulp later on, you just need to do whatever changes you need (Gruntfile instead of Gulpfile, edit package.json etc), and yet users of the project will still start the build process with npm run build.
It’s invisible to them (except perhaps running npm install again)!
You’re hiding internals that they do not necessarily need to know about, so it’s a good abstraction. Seriously—you won’t even need to update your getting started guide! Good stuff.
Hope that helps!