How to avoid global installs with NPM scripts
Recently, I heard from a friend that he doesn’t know how to use Gulp and TypeScript locally, he only knows how to install them globally. I thought it could be an issue for others, and that’s why I decided to write this post.
Using globally installed NPM packages can be very problematic, especially if you need these in different versions in a variety of projects. If you rely on global packages you don’t know what the dependencies of your project really are. It is better to have everything in one place without part of your dependencies in global and the other part of your dependencies in local space.
To use gulp and tsc (TypeScript compiler) without polluting your global, you simply install it locally with a command like this: npm install gulp typescript --save-dev
and then you use the power of
NPM scripts.
As you can see, in that link there are a lot of predefined scripts but I will show you how to define custom ones.
All you have to do is simply to define the name of script in the scripts section in the package.json. This is an example from one of my projects:
"scripts": {
"tsc": "tsc -w",
"typings": "typings",
"build-dev": "gulp build-dev",
"build-prod": "gulp build-prod",
"postinstall": "concurrently \"typings install\" \"npm run build-dev\"",
"start": " http-server "
},
I have defined four custom scripts and two predefined here. You can run custom scripts with a command like this:
npm run tsc
You must execute this command in the root folder of your project (where your package.json is).
Running a predefined script is as simple as: npm start
, you don’t have to put run.
Some scripts are run automatically, for example postinstall. This script is run after the package is installed. In my case, after the package was installed, I installed typings and I rebuilt the libraries using the script defined above which is build-dev. As you can see, you can execute other scripts in NPM scripts and you also have access to the commands which are located in the node_modules/.bin of your project. In this location, you will find your commands gulp and tsc and other locally installed packages.
The scripts defined in package.json look for commands inside this location and if they didn’t find one they then check your global packages. You can also run locally installed packages with a command like this: node_modules/.bin/gulp
but as you can see, this is a lot of typing and over time it can be very annoying. It is much better to use NPM scripts. I hope I have helped someone by writing this post.
Comments
comments powered by Disqus