Vue3中配置eslint+prettier代码检测与格式化
项目使用vue-cli创建,其中依赖如下,主要看dev依赖package.json
安装依赖
npm install eslint eslint-config-prettier eslint-plugin-prettier eslint-plugin-vue prettier
1.配置eslint
在根目录下依次创建.eslintrc.js和.eslintignore文件
//.eslintrc.js
module.exports = {
root: true,
env: {
node: true,
},
extends: ['plugin:vue/vue3-essential', 'eslint:recommended', 'plugin:prettier/recommended'],
parserOptions: {
parser: '@babel/eslint-parser',
},
rules: {
'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'no-undef': 0, //使用未声名的变量
'no-unused-vars': 0,
},
}
//eslintignore
build/*.js
src/assets
public
dist
.DS_Store
node_modules
/dist
2.配置prettier
在根目录下依次创建.prettier.js和.prettierignore文件
.prettierrc.js主要存放代码格式化时遵从的规则,而.prettierignore则表示不对哪些文件进行格式化,接下来让我们来看看基本配置。
//.prettierrc.js
module.exports = {
// 箭头函数只有一个参数的时候可以忽略括号
arrowParens: 'avoid',
// 括号内部不要出现空格
bracketSpacing: true,
// 行结束符使用 Unix 格式
endOfLine: 'auto',
// true: Put > on the last line instead of at a new line
jsxBracketSameLine: false,
// 行宽
printWidth: 100,
// 换行方式
proseWrap: 'preserve',
// 分号
semi: false,
// 使用单引号
singleQuote: true,
// 缩进
tabWidth: 2,
// 使用 tab 缩进
useTabs: false,
// 后置逗号,多行对象、数组在最后一行增加逗号
trailingComma: 'es5',
}
更多配置项可前往prettier官网查看,其中Playground还提供可视化配置,非常方便。
//.prettierignore 可以根据自己的目录结构自行添加
/dist/*
.local
.output.js
/node_modules/**
**/*.svg
**/*.sh
/.vscode
/public/*
3.VScode配置
formatOnSave会在保存时自动格式化代码,你也可以在全局配置该选项,editor.codeActionsOnSave则是为了消除eslint与prettier在编辑器中的冲突。
{
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit"
},
}
4.批量格式化命令
在项目当中,我们可能在开发结束后,提交代码时才会对代码进行格式处理,为了省去一个一个文件的去格式化,我们可以在package.json中配置格式化命令。
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint",
"format":"prettier --write \"src/**/*.+(js|vue)\""
},