Formatting Vue.js Code with ESLint & Prettier

Joshua Bemenderfer

Prettier roared to life last year as the solution to all your code formatting problems. It takes the code you write, transforms it into an AST, then prints that AST in a, well, prettier format. Its goal is to automate the work of formatting code to be super readable. While it was rapidly adopted by the React and larger JavaScript (and even CSS!) ecosystems, Vue users were initially left in the dark, due to lack of support for Single-File Components (.vue files). However, as of Prettier 1.10, *.vue files are officially supported! 🎉

Prettier is designed to be easy to integrate with ESLint, which is what most Vue configurations use. We’ll walk you through setting up Prettier with ESLint and Vue in this guide.

Dependencies

Go ahead and start a new Vue project using vue-cli 3.0 beta and the default options. $ vue create my-new-project and hitting enter a couple times should be sufficient.

Then you’ll want to install prettier globally from NPM, if you haven’t already. (It can be installed on a per-project basis, but that’s not really recommended.)

$ npm install --global prettier

Finally, go ahead and add the eslint-prettier integration packages to your project:

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

The Config

If you’re using a project created with vue-cli 3.0 beta, you’ll find the ESLint config inside package.json under the eslintConfig property.

Go ahead and add "plugin:prettier/recommended", to the extends sub-property after "plugin:vue/essential",, to enable prettier support in ESLint with the default settings.

package.json


  "eslintConfig": {
    "root": true,
    "extends": [
      "plugin:vue/essential",
      "plugin:prettier/recommended",
      "eslint:recommended"
    ]
  },

Otherwise, if you’re using a pre-existing project with eslint already set up, then make the same modifications to .eslintrc.js or whichever ESLint configuration format you’re using.

.eslintrc.js


module.exports = {
  "root": true,
  "extends": [
    "plugin:vue/essential",
    "plugin:prettier/recommended",
    "eslint:recommended"
  ],
}

If you don’t have eslint installed or set up for Vue yet, we have just the guide for you! This guide also shows how to configure VSCode and Atom to lint your Vue files in realtime.

Once you’ve made those changes, you should find that running eslint --fix will pull in Prettier to reformat and prettify your JS and Vue files for you! No more worrying/arguing/pulling out hair over code styles! They’ll be automatically enforced for everyone using eslint.

  Tweet It

🕵 Search Results

🔎 Searching...

Sponsored by #native_company# — Learn More
#native_title# #native_desc#
#native_cta#