Vue中使用eslint和prettier格式化代码
前言使用eslint+prettier好处:避免运行时因格式问题报错方便团队合作,代码风格统一0. 建立项目利用Vue-cli3建立Vue项目时,一定要选上Linter/Formatter,然后选择 ESLint + Prettier1. 安装vscode插件首先在vscode中安装如下三个插件:eslintveturprettier2. 配置.eslintrc.js(根目录下找)注:代码缩进不是
·
前言
使用eslint+prettier好处:
- 避免运行时因格式问题报错
- 方便团队合作,代码风格统一
0. 建立项目
利用Vue-cli3建立Vue项目时,一定要选上Linter/Formatter,然后选择 ESLint + Prettier
1. 安装vscode插件
首先在vscode中安装如下三个插件:
- eslint
- vetur
- prettier
2. 配置
-
.eslintrc.js(根目录下找)
注:代码缩进不是4个空格报错。 -
.prettierrc
在文件根目录下创建.prettierrc对prettier格式化进行自定义规则设置,以下为我添加的规则
{
/* 单引号包含字符串 */
"singleQuote": true,
/* 不添加末尾分号 */
"semi": false,
/* 在对象属性添加空格 */
"bracketSpacing": true,
/* 优化html闭合标签不换行的问题 */
"htmlWhitespaceSensitivity": "ignore",
/* 只有一个参数的箭头函数的参数是否带圆括号(默认avoid) */
"arrowParens": "avoid"
}
- .editorconfig
在文件根目录下创建.editorconfig,内容如下:
root = true
[*]
charset = utf-8
# 缩进风格为空格
indent_style = space
# 缩进大小为4
indent_size = 4
## 表示以Unix风格的换行符结尾
# end_of_line = lf
# insert_final_newline = true
# # 设为true表示会除去换行行首的任意空白字符。
# trim_trailing_whitespace = true
- setting.json(vscode中自带的setting)
user setting:
{
"git.path": "E:/Git/bin/git.exe",
"vetur.validation.template": true,
"git.autofetch": true,
"editor.tabSize": 4,
"eslint.autoFixOnSave": true,
// "editor.detectIndentation": false,
"vetur.format.options.tabSize": 4,//四格缩进
// "vetur.format.styleInitialIndent": true,
// "vetur.format.options.useTabs": true,
// "vetur.format.scriptInitialIndent": true,
"vetur.format.defaultFormatter.html": "js-beautify-html",
"vetur.format.defaultFormatterOptions": {
"js-beautify-html": {
"wrap_attributes": "auto",//属性不换行
"end_with_newline": false
}
// "prettier": {
// // Prettier option here
// "semi": false, //要分号
// "singleQuote": true //要单引号
// }
},
"gitlens.gitExplorer.files.layout": "list",
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"update.channel": "none",
"eslint.validate": [
"javascript",
"javascriptreact",
{
"language": "vue",
"autoFix": true
},
"vue"
],
"window.zoomLevel": 0
}
3. 最后
配置eslint和prettier可真是要了我的老命。。。。还好最后自己比较满意,大家可以根据自己习惯自行调配规则。
注:
先用 alt+shift+f 格式化代码,然后看报错手动调整直到没有error和warning。
如上图warning出现在第9行第十个字符处。
更多推荐
所有评论(0)