You may define scripts in your package.json
, for example:
{
"name": "your-package",
"version": "1.0.0",
"description": "",
"main": "index.js",
"author": "",
"license": "ISC",
"dependencies": {},
"devDependencies": {},
"scripts": {
"echo": "echo hello!"
}
}
To run the echo
script, run npm run echo
from the command line. Arbitrary scripts, such as echo
above, have to be be run with npm run <script name>
. npm also has a number of official scripts that it runs at certain stages of the package's life (like preinstall
). See here for the entire overview of how npm handles script fields.
npm scripts are used most often for things like starting a server, building the project, and running tests. Here's a more realistic example:
"scripts": {
"test": "mocha tests",
"start": "pm2 start index.js"
}
In the scripts
entries, command-line programs like mocha
will work when installed either globally or locally. If the command-line entry does not exist in the system PATH, npm will also check your locally installed packages.
If your scripts become very long, they can be split into parts, like this:
"scripts": {
"very-complex-command": "npm run chain-1 && npm run chain-2",
"chain-1": "webpack",
"chain-2": "node app.js"
}