CleanCrispCode CleanCrispCode - 1 year ago 71
Node.js Question

about "scripts" key in package.json

Can anyone explain what is the purpose of "scripts" key in package.json file.

While learning Angular 2 , I came across below script in package.json file,
was not sure whats the use of this key.

"scripts": {
"postinstall": "npm run typings install",
"tsc": "tsc",
"tsc:w": "tsc -w",
"start": "concurrent \"node ./bin/www\" \"npm run tsc:w\"",
"typings" : "typings"

Answer Source

The scripts key provides a convenient place to define project-specific automation scripts right there in your already-mandatory package.json. This helps developers just type something simple, like npm run cover or npm run deploy and have a possibly-complex series of steps (with very specific file locations or program arguments) kicked off. This avoids typing long command lines, and it avoids errors. For example, one of my projects includes these commands:

"scripts": {
    "cover": "cd source/js/jutil && istanbul cover _mocha -- -R spec && open coverage/lcov-report/jutil/index.html",
    "test": "cd source/js/jutil && mocha",
    "deploy": "(git diff --quiet --exit-code --cached || git commit -a -m 'deploy') && git push heroku master && heroku open",
    "start": "gulp start"

I can quickly run a test, a coverage test, or deploy to a cloud host with just a few words, and never having to remember the detailed command-line options or file locations.

Beware, however. There is much controversy in the JavaScript / node.js community about the "best" or "right" place to define such automation.

Many developers prefer to shift automation to separate "task runners" / "build systems" such as gulp, grunt, or even good ole Unix make. For those projects, the scripts tag will be empty or nearly so. (npm init by default generates at least a single key, for test.) Instead you need to look to their gulpfile.js, Gruntfile, or Makefile.

Other developers have rejected the idea of becoming build-system mechanics and/or separating out build configuration. They often prefer to put "a few simple scripts" directly in package.json and call it a day.

In my experience, "a few simple commands" is a great goal but scripting complexity can quickly outstrip it. This is especially true in larger projects with many different assets and asset types, for which live-rebuild or live-reload are desired, or that have more than a few deployment options. I usually end up with gulp doing the heavy-lifting, but perhaps a few scripts that can truly be concisely stated still resident in package.json. "Your mileage may vary."