Configure ESLint and Prettier for Vue/Nuxt.js project in VS Code
I'd like to share my recommended ESLint and Prettier configuration for a Vue.js project built with Nuxt.js (loving it!). As preferred IDE, I am using - guess what? - VS Code. This article is just considered as simple dev notes without digging any deeper, and it's based on my current "best practices".
Install ESLint and Prettier with all recommended plugins into devDependencies
using yarn
(you might as well use npm
):
$ yarn add --dev eslint eslint-plugin-nuxt eslint-plugin-vue
$ yarn add --dev eslint-config-prettier prettier eslint-plugin-prettier
$ yarn add --dev @nuxtjs/eslint-module @nuxtjs/eslint-config @babel/eslint-parser
The following lines were added to my package.json
(only an extract, showing you the current versions as of Aug 2021):
{
"devDependencies": {
"@babel/eslint-parser": "^7.15.0",
"@nuxtjs/eslint-config": "^6.0.1",
"@nuxtjs/eslint-module": "^3.0.2",
"eslint": "^7.32.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-nuxt": "^2.0.0",
"eslint-plugin-prettier": "^3.4.0",
"eslint-plugin-vue": "^7.15.1",
"prettier": "^2.3.2"
}
}
Configure ESLint in .eslintrc.js
(in your project root):
module.exports = {
root: true,
env: {
browser: true,
node: true,
},
parserOptions: {
parser: '@babel/eslint-parser',
requireConfigFile: false,
},
extends: [
'@nuxtjs',
'plugin:nuxt/recommended',
'prettier'
],
plugins: ['prettier'],
rules: {
'prettier/prettier': ['error'],
'vue/html-indent': ['error', 4],
'vue/singleline-html-element-content-newline': 0,
'vue/component-name-in-template-casing': ['error', 'PascalCase'],
'vue/valid-v-slot': [
'error',
{
allowModifiers: true,
},
],
},
globals: {
_: true,
},
}
Configure Prettier in .prettierrc
(again in your project root):
{
"semi": false,
"singleQuote": true,
"tabWidth": 4,
"printWidth": 120
}
Also create .prettierignore
:
# Ignore artifacts:
build
coverage
Configure VS Code Editor: Format on Save to apply auto formatting upon saving, which you can also restrict to specific languages, .vscode/settings.json
:
{
"vetur.format.defaultFormatter.html": "none",
// Set the default
"editor.formatOnSave": false,
// Enable per-language
"[javascript]": {
"editor.formatOnSave": true
},
"[vue]": {
"editor.formatOnSave": true
}
}
Now, open any .vue
or .js
file, fire Cmd-S
to save the file and see the magic. If it won't yet work for you, consider restarting VSCode.
Don't worry, a file only gets formatted if you explicitely hit Cmd-S
. You can still use autoSave
for regular saving, which would not invoke auto-formatting of the whole file. That's the relevant global VS Code user settings (can be found in $HOME/Library/Application Support/Code/User/settings.json
on macOS):
{
"files.autoSave": "afterDelay",
"prettier.printWidth": 81,
}
Done. Happy clean coding!