ESLint and Prettier with Vite and Vue.js 3

Part 2 of 3 in our How to Structure a Large Scale Vue.js Application series.
Written by Daniel Kelly

In the previous article of the "How to Structure a Large Scale Vue Application" series, we took a look at some standards that you can employ in your Vue.js application to keep your codebase predictable, easy to navigate, and understandable. Another step you can take to improve the developer experience when building a large scale application, especially with a team, is to setup some automated process for code linting and formatting.

Perhaps you've never used such tools before. Let's briefly take a look at the "what and why" of linting and formatting and then jump into setting up ESLint and Prettier with your Vite powered Vue project. If you're already familiar with linting and formatting with ESLint and Prettier then feel free to skip to part about setting them up with Vite.

It's also worth noting, that most of the steps for setting up ESLint and Prettier described here will also work outside of a Vite project, such as with your Laravel + Vue powered applications, and so on.

Linting with ESLint

screenshot of ESLint Homepage

So, what is linting? Linting is the automated process of statically analyzing code for potential errors. Typically, linting can do things like detect syntax errors, like a missing comma, or warn you that a file has a variable defined that is never used. Linting isn't going to save your code from any business logic flaws but it is going to make sure your code is syntactically accurate and follows some best practices. So, what solutions do we have available for linting our Vue.js projects? The go to linting tool for JavaScript is ESLint.

ESLint is not only able to detect errors in your code, but in many cases, can even automatically correct them for you. It can run as a command line tool and is also integrated into most common IDEs. These IDE integrations are invaluable as they allow the errors detected by ESLint to be revealed directly in the file where you're editing. Typically this consists of a squiggly red line under the offending code, much like spellcheck but for your code! The IDE integrations also usually make it so that you can run the command to automatically fix things with a keyboard shortcut or on the save of the file.

gif of eslint in action

Code Formatting with Prettier

screenshot of Prettier homepage

Now let's talk about formatting. What's the difference between formatting and linting? While linting is focused on detecting errors, formatting is about ensuring your code adheres to some consistent formatting rules such as tab width, single quotes or double quotes, trailing commas, end of line semi-colons, and more.

Such formatting rules ensure that your code looks consistent even when developed by different developers perhaps even in different IDEs. It also keeps you from having to make certain formatting decisions yourself (should I terminate my lines with a semi-colon or not?). Instead you just write the code any way you'd like and let the formatter reformat it for you when you're done.

So how do we get formatting working for us? If you're already using ESLint you actually already have some formatting working for you. ESLint is cool like that and kind of performs double duty linting and formattting. Even though ESLint takes care of some formatting for us though, another tool, called Prettier, is more comprehensive and is really considered more of the industry standard. Prettier can be paired together with ESLint and together they're a powerhouse for all your linting and formatting needs.

One of the best parts about Prettier is that it is highly opinionated by design. While that's a trait you might not want in a fishing buddy, for a code formatter it means less time configuring and worrying about standards and just doing what you do best, writing quality code!

Like ESlint, Prettier integrates well with most IDEs and has the same integration features as described for ESLint earlier.

gif of ESLint in action

Setting up with a Vite Project

Now that we know what ESLint and Prettier are and what advantages they provide let's get them setup in a shiny new Vue.js project powered by Vite. Unlike Vue-CLI, Vite does not have these tools auto configurable for us via the command line setup process, so we'll have to get them installed and configured ourself. But, not to worry, I'll walk you through the whole process step by step.

Create Vite Project

If you don't already have a project created by Vite you can run this command:

npm init [email protected]

Follow the prompts and then change into the directory of the newly created project.

Installing Prettier

We'll start by installing prettier. We can do this with the following command:

npm install --save-dev --save-exact prettier

Next we'll create a config file for prettier. Since, prettier aims to be configuration free out of the box, the content of that config file can just be an empty object. We're only adding it, as some IDEs use it's presence to detect prettier. If you want to configure one of the few options that Prettier does provide see the Prettier docs for config options.

echo {}> .prettierrc.json

Nice, that should do it for prettier. Now let's setup ESLint.

Installing ESLint

We can install ESLint and the vue plugin for ESLint with the following command:

npm install --save-dev eslint eslint-plugin-vue

Next, we'll configure ESLint by creating a .eslintrc.js file with the following configuration so that it's configured to use the ESLint recommend rules as well as the recommended rules for Vue 3.

module.exports = {
  env: {
    node: true,
  },
  extends: [
    'eslint:recommended',
    'plugin:vue/vue3-recommended',
  ],
  rules: {
    // override/add rules settings here, such as:
    // 'vue/no-unused-vars': 'error'
  }
}

Visit the eslint-plugin-vue docs to see the other configurations available for use with Vue 3 for less strict options if desired. The different configurations correspond to the 3 different priorities in the Vue.js 3 style guide.

Finally, we'll turn off ESLint's formatting rules that would conflict with Prettier. If we didn't do this step, we'd have a never ending death match between the 2 that looks something like this:

deathmatch between ESLint and Prettier, it ain't pretty

If you've skipped this step before you know what a headache it can be. If you weren't aware of this step when setting up Prettier and ESLint before you'd likely never want to use either of the tools again! Luckily it's easily fixable.

Learn Vue.js 3 With Vue School

We just need to install the eslint-config-prettier config. This disables the formatting rules in ESLint that Prettier is going to be responsible for handling.

npm install eslint-config-prettier --save-dev

And register the config in .eslintrc.js file under extends. Make sure it's the last config defined in the extends array as the order of the configs determine duplicate rules in different configs are handled (later configs override previous ones)!

//.eslintrc.js
extends: [
  'eslint:recommended',
  "plugin:vue/vue3-recommended",
  "**prettier**"
],

Running from the Command Line

At this point we should be set to have ESLint report on and correct fixable errors and have Prettier reformat our source code. Let's add the following two items to the scripts section of the package.json.

"scripts":{
  //...
  "lint": "eslint --ext .js,.vue --ignore-path .gitignore --fix src",
  "format": "prettier .  --write"
}

The lint command defined here would be great for running linting in your CI/CD pipeline or just for testing manually in the terminal. You can see either work quickly by running the respective commands, however this is not necessarily how you want to continually use them throughout the development process.

Setting up ESLint and Prettier with VS Code for Vue 3

To streamline your workflow you'll want to integrate the 2 tools with your IDE. Doing so will allow you to have errors underlined for you in real time and also provide automatic fixing of ESLint errors and prettier formatting on file save. Talk about a time saver! Since VS Code is a free and popular IDE and the IDE I use, let's take a look at how to integrate ESLint and Prettier with VS Code for your Vite powered Vue.js 3 project.

First you'll need to install the 2 corresponding plugins for Prettier and ESLint. You'll also want to install Vetur if you haven't already, as it provides syntax highlighting and more for .vue files.

Next, in your VS code settings you should provide the following to turn off Vetur's validation of the template and let ESLint handle it based off of the rules in the .eslintrc.js file.

// Code/User/settings.json
"vetur.validation.template": false

Now if you open the HelloWorld component you can see ESLint in action. You can see the yellow squiggly line underneath msg: String and if you hover over it you'll see more info about why ESLint is warning you about it. In this case, it's because of the rule vue/require-default-prop.

screenshot of ESLint working with VS Code providing a yellow squiggly line to indicate a warning

And so to fix the issue we can do one of 2 things.

  1. We could turn the vue/require-default-prop rule off in the .eslintrc.js file if we want to allow props without default values.
// Code/User/settings.json
rules: {
  //...
  "vue/require-default-prop": "off",
},
  1. Or we change the code to adhere to the rule by providing a default value and the squiggly line disappears! Very nice!

screenshot of fixing the error by making the code conform to the ESLint rules

Now we've got ESLint reporting the errors directly in the file but we don't have any automation setup for Prettier to reformat the code or for ESLint to auto correct fixable issues. We can tell VS code to do both of these things on save by adding the following to our VS code settings.

// Code/User/settings.json
{
  "editor.formatOnSave": true,
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },
}

We should also ensure that our vue and js files have prettier configured as the default formatter with the following settings:

// Code/User/settings.json
"[vue]": {
  "editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[javascript]": {
  "editor.defaultFormatter": "esbenp.prettier-vscode"
},

Now if you open up App.vue, and tab the image over one and save it'll automatically pop back to where it should be! That's Prettier at work!

gif of Prettier reformatting App.vue

If you change the image to loop over an imaginary items array placing the key before the v-for like so:

<img :key="i" v-for="i in items" alt="Vue logo" src="./assets/logo.png" />

you'll see that ESLint kicks the vue/attributes-order rule into action automatically fixes the issue on save. That's so handy!

ESLint fixes vue attribute order

ESLint Errors in the Browser

For most developers and teams, the setup that we have at this point is probably enough to be productive. However, if you want to take it one step further you can install the Vite ESLint plugin to see your ESLint issues overlayed over your application in the browser.

ESLint error overlay in the browser with Vite

This makes those ESLint errors that aren't automatically fixable impossible to ignore. I know some developers who love this and others who find it super annoying, so install it if you want, otherwise just make sure you pay extra attention to those red squiggles in your IDE.

Install vite-plugin-eslint by running

npm install vite-plugin-eslint --save-dev

Then register the plugin by importing it and and adding it as a plugin in vite.config.js

import { defineConfig } from 'vite';
import eslintPlugin from 'vite-plugin-eslint';

export default defineConfig({
  plugins: [eslintPlugin()],
});

And that's it, any ESLint error will now be reported in the browser! If it doesn't for you, try restarting the development server.

Resources

Lastly, I know that following all the different plugins, configs, tools, etc when it comes to setting up linting and formatting can be a little intimidating so here's a list of all the different resources with links to their docs and a short description of the benefit they provide.

Conclusion

When creating any large scale project in Vue, it's always a good idea to setup an automated process for linting and formatting so that code is consistent and error free. While Vue-CLI provides a way to set this up out of the box, the faster and more modern build tool Vite does not. ESLint and Prettier can be a little intimidating to setup especially due to all the different environments they should ideally run in (terminal, IDE, browser) but with a little patience you can set them up one and done for your Vite powered Vue.js projects and reap the benefits throughout the life of the project.

Looking into leveling up your business?

We help companies all around the world build Vue applications more efficiently. Do you feel your team would benefit from professional Vue training or consulting? Or perhaps you need some extra hands developing your next milestone?
We are happy to hear your business needs and figure how we can help you out. Check out our business pricing for team training or contact us for business inquires any time!

Learn Vue.js 3 With Vue School

Leave a Reply

Your email address will not be published. Required fields are marked *

Up Next:

How to Structure a Large Scale Vue.js Application

How to Structure a Large Scale Vue.js Application