Linting

Linting is the process of applying static analysis to your codebase to detect issues or enforce style guidelines. It is very useful when working with dynamically typed languages such as javascript. ESLint is the standard linter, it allows you to define sets of rules to run against your codebase, or use plugins to use a pre-defined set. We will use the Vue eslint plugin to enforce the recommended rules for a Vue application.

There are quite a few npm packages we need to install to enable linting:

npm install --save-dev eslint eslint-plugin-import eslint-plugin-node eslint-plugin-promise eslint-plugin-standard eslint-config-standard babel-eslint eslint-loader eslint-plugin-vue

Once this is done, we need to tell eslint which rules we want to use, create a file called .eslintrc.js in the project root and and add these settings:

module.exports = {

parserOptions: {

parser: 'babel-eslint'

},

extends: [

'plugin:vue/recommended',

'standard'

],

plugins: [

'vue'

]

}

Here we are telling eslint that we want to use babel to parse our javascript and then apply the standard linting rules and the recommended rules from the vue plugin.

The easiest way to run ESLint is via an npm script. Add this to package.json in the scripts section:

"lint": "eslint --ext .js,.vue src"

We’re running ESLint against anything in our src folder with the file extension .js or .vue. Running this now and you should actually get an error already.

This is pointing at these lines in our index.js, I have the eslint extension for VSCode installed so if I open this file now I can see another visual cue that something is wrong.

There are various ways to fix this, we could export the new Vue object for instance, however let’s tell ESLint that this line is actually OK and we want it to ignore it. Add this comment immediately before the offending code:

/* eslint-disable-next-line no-new */

Now when you rerun our lint script it should report no errors.

ESLint also supports autofixing some classes of errors, I like to add a shortcut script to my npm config to allow me to run the autofix when required:

"lint:fix": "eslint --ext .js,.vue src --fix"

Once our linting is configured to run on-demand we want to change our webpack build so it runs automatically. For this we need to install the webpack loader:

npm install --save-dev eslint-loader

And change our webpack config to add a rule to associate our .js and .vue files with the ESLint loader:

{

test: /\.(js|vue)$/,

use: 'eslint-loader',

enforce: 'pre'

}

This rule has one change to our others, enforce: ‘pre’. This means the ESLint loader is a pre-loader, it will run before the other loaders and apply the linting rules before the babel-loader kicks in and start processing the javascript.