NPM package.json Scripts

Image By Joshua Aragon

I've been messing around with node & npm for ages but only recently realised the power of npm scripts. When they're executed node_modules/bin is added to the environment path, so you can execute modules which are installed locally. That means things like babel or mocha can be merely installed as dev dependencies which is much easier than trying to manage global dependencies from within a package. In late 2016 the node community has begun moving away from build tools like grunt and gulp in favor of npm scripts, and why not? If you can remove dependencies / complexity from a package without losing functionality then it seems like a good idea to me. Having said that, in the last few months I've been working mostly with the awesome Metalsmith, which is basically gulp or grunt focused on building static sites.. so I can't really brag about being build tool free. I've noticed that these scripts are very portable between packages that you're working on, provided of course that you stick to a consistent package structure. So my current scripts object looks like this:

  "scripts": {
    "docs": "rm -fr ./docs/* && docker -o ./docs -I -x dist,,test/fixtures,node_modules,docs",
    "readme": "node-readme",
    "gh-pages": "gh-pages -d docs",
    "build": "npm run babel:node4 && npm run babel:node6 && npm run readme && npm run docs && cp docs/ docs/index.html && npm run gh-pages",
    "babel:node4": "cross-env NODE_ENV=node4 babel lib -d dist/node4",
    "babel:node6": "cross-env NODE_ENV=node6 babel lib -d dist",
    "test:coverage": "cross-env NODE_ENV=test nyc --reporter=lcov --reporter=text --check-coverage --lines 100 npm run test",
    "test": "cross-env NODE_ENV=test mocha --compilers js:babel-register test",
    "test:watch": "cross-env NODE_ENV=test mocha --compilers js:babel-register --watch test",
    "version": "npm run build",
    "postversion": "git push && git push --tags"

You'll notice there's quite a bit of recursion. I've tried to organise this generally into scripts which do one thing, and scripts which run several of the "do one thing" scripts.

Levi Wheatcroft Profile Picture

About the Author

Levi is an accountant and web technology enthusiast from Western Australia. Find out more about his firm or his web stuff.