Tutorial
Formatting Vue.js Code with ESLint & Prettier
While this tutorial has content that we believe is of great benefit to our community, we have not yet tested or edited it to ensure you have an error-free learning experience. It's on our list, and we're working on it! You can help us out by using the "report an issue" button at the bottom of the tutorial.
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.
"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.
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.