Automatic pre-build linting with npm scripts

Mattias Wikström
Go back

Linting is boring and easy to forget, automate!

This short tip is for anyone that:

  1. Has read through Elins wonderful explanation on the scripts in package.json and gotten comfortable with writing npm run build to transpile your commonjs-modules and jsx-code to browser-friendly vanilla JavaScript.

  2. Has gone through my post on using ESLint to lint your React code and can write npm run lint to get the linter going.

  3. Wants to connect these two commands.

The idea is that no un-linted code should get built, so optimally you should go npm run lint, wait a few seconds to see if everything is OK and then write npm run build to build your linted, kosher code. Well… having to write the same two commands over and over again gets really tedious, really fast.

Thankfully npm scripts come prepacked with the awesomeness that any script you add to your package.json can have a script that gets called automatically before and/of after the called script. This is done by simply creating a new script with pre or post added to name of the script that you want to add the hook to.

To clearify, if I wanted to lint my code automatically before every build, then echo “phew, I am pooped!” after the build has succeeded my scripts would look like this:

// package.json
"scripts": {
    "lint": "eslint src/**",
    "prebuild": "npm run lint",
    "build": "browserify --debug -t [reactify --es6] src/main.js > bundle.js",
    "postbuild": "echo 'phew, I am pooped!'"

So, doing this we get the best of both worlds - linting before every build and you only have to write one command. Pretty neat, huh?

The only problem now is that you actually have to follow the linter rules. No more Mr Sloppy!