My latest projects at work have evolved from being PHP / Laravel applications with sprinklings of Vue JS on the front end to being almost entirely Vue JS components driving the frontend with Laravel backends.
Luckily adding eslint and defining rules for your
.vue files to follow is pretty straight forward.
Whilst you can install eslint globally on your system I’d recommend adding it on a per-project basis so that you can include running eslint as a build step within your CI/CD process.
Add eslint to your projects package.json file.
Create a base configuration
The above command will ask you a number of questions for my laravel projects I use the following:
Are you using ECMAScript 6 features? Yes
You’ll end up with a new file called
.eslintr.json within your project root that has the following content generated as a result of the responses to the questions above.
At this point eslint is now set up and ready to be used in your project.
Running the above should give you some sort output like the following (unless you have JS that adheres to all of the standards of course!):
Running the same command with the
--fix argument should get eslint to attempt to fix as many of the above errors as it can.
Right now we can lint
.js files but if we’re using
.vue single file components then trying to run eslint on them will give us an error like this:
./node_modules/.bin/eslint ./resources/assets/js/components/*.vue --fix
We need to tell eslint how to parse
.vue files and what rules to apply to them.
Next register the
eslint-vue-plugin in your
.eslint.json file by adding it to the extends block:
There are actually a number of different default config values for the eslint vue plugin that add increasingly stricter rule sets to be applied to the linter. They are as follows:
Now running eslint against
.vue files will result in expected output:
Finally we can add eslint to our build process. For my work projects I use gitlab ci/cd.
Start by adding a new
script to our
package.json file called
eslint which we can call from gitlab:
This script tells eslint will look for all files with the
.vue extension recursively within the
test folders of my project.
Next lets update our
.gitlab-ci.yml file to add the new build step.
If you don’t have a stage for
syntax defined first do that:
# Define pipeline stages
Next add the job for eslint:
And that’s it! Commit some code and watch your CI process check the code for errors!
I found that I had a few rules defined by default that bugged me so i turned them off. My current
.eslint.json file looks like this: