Automate code linting with webpack and JSHint

Wednesday, Feb 11 2015

In this post, we are going to configure webpack to automatically check your code with JSHint with each build.

First of all, you need to install the jshint webpack loader. Assuming you are using npm, type npm install jshint-loader in your project directory. This should download jshint-loader into your local node_modules directory and make it available to webpack.

Now let’s look at how to configure the webpack JSHint loader. If you want to check your code before any transformations are applied (for instance, because you do not want JSHint to check code generated by a transpiler) you should configure JSHint as a preloader. If you want to check your code after all transforms have been applied, you should configure JSHInt as a postloader. If you use React with JSX, you should configure JSHint as a postloader, because JSHint does not understand JSX, so JSX should be transpiled to JavaScript beforehand.

The configuration syntax is the same as for any webpack loader:

module: {
   postLoaders: [
     {
       test: /\.js$/,
       exclude: /node_modules/, // do not lint third-party code
       loader: 'jshint-loader'
      }
   ]
}

Now, when you run webpack, you should see an error report of this type on the console:

WARNING in ./sample.js
jshint results in errors
  Expected an assignment or function call and instead saw an expression. @ line 2 char 1
    x

  Missing semicolon. @ line 2 char 2

By default, jshint-loader will log any JSHint messages as webpack warnings (I must confess it is not very clear to me what the difference between a webpack error and warning is, since neither fails the build). Even if JSHint emits errors or warnings, webpack will not fail the build (that is, it will still produce the output files). If you want to change these behaviours, you can pass additional configuration to jshint-loader like so

/* Put this in your 'module' section  of the webpack config */
jshint: {
       // Display JSHint messages as webpack errors
  emitErrors: true,

        // fail the build on JSHInt errors
  failOnHint: false,
}

Notice that, as of jshint-loader 0.8.2, failOnHint: true will cause the build to fail on both JSHint errors and JSHint warnings, even if emitErrors is set to false.