npm has some lesser known features. Today I feel like highlighting the npm scripts features for others to exploit too.
Basic
This feature is basically a list of names with associated with commands to do certain jobs. So instead of remembering complex scripts to automate your software you use short ones in the form of npm run [script-name]
.
To use npm scripts you need a scripts object in your package.json file, this is where the name and command are stored.
{
"name": "Demo App",
"scripts": {
"name": "command",
"deploy": "git push heroku master"
}
These commands are now able to use with npm run [script-name]
.
Hooks
Using a postinstall
script will run a command just after your npm modules have been installed. This is great for installing other dependencies your stack might need, let’s say for example your bower components.
{
"dependencies": {
"bower": "*"
},
"scripts": {
"postinstall": "./node_modules/bower/bin/bower install"
}
}
Other script hooks include are documented on npm’s site.
Overides
You’re likely using npm start
to run your app, well if your “main” file isn’t what suits your app structure to start the app then overwrite the command using a script!
{
"scripts": {
"start": "node ./bin/start-enviroment"
}
}
As the npm documentation states, using the override for install
is discouraged. Here the prepublish
override should be used so that a module is all packed up and ready to use when the module is installed.
The time to use these
Now! There’s not always a need to use tools like Grunt and Gulp. If you’ve already got npm installed, why not just use that to cut down on tooling.