集成editorconfig配置
EditorConfig可以让不同系统电脑,或者不同IDE编辑器中,让不同的开发者保持一致的编码风格,Vue官方的editorconfig内容如下
js
# https://editorconfig.org
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
insert_final_newline = false
trim_trailing_whitespace = false
- charset 设置文件的字符集
- indent_style 缩进风格
- indent_size 缩进大小
- end_of_line 换行类型 (lf | cr | crlf)
- insert_final_newline 始终在文件末尾插入一个新行
- trim_trailing_whitespace 去除行首的任意空白字符
VSCode需要安装一个插件:EditorConfig for VS Code
使用prettier工具
Prettier是一款强大的代码格式化工具,基本上前端用到的文件格式它都可以搞定
1、install:npm install prettier -D 2、配置 .prettierrc 文件
js
{
"useTabs": false,
"tabWidth": 2,
"printWidth": 80,
"singleQuote": true,
"trailingComma": "none",
"semi": false
}
- useTabs: 使用tab缩进还是空格缩进
- tabWidth:tab是空格的情况下,是几个空格
- printWidth:当前行字符的长度
- singleQuote:使用单引号还是双引号,选择true,使用单引号
- trailingComma:在多行输入的尾逗号是否添加
- semi:语句末尾是否要加分号,默认值true,选择false表示不加
3、创建 .prettierignore 忽略文件
js
/dist/*
.local
.output.js
/node_modules/**
**/*.svg
**/*.sh
/public/*
/.npmrc/**
4、需要在VSCode中安装prettier插件 『Prettier - Code formatter』 5、代码格式化: 可以在package.json 的script脚本下配置
json
"prettier": "prettier --write ."
使用 npm run prettier,会找到 node_modules下的.bin目录下的prettier工具格式化项目里的所有文件(prettierignore里配置的忽略文件不会被格式化)
使用ESLint检测
1、创建Vue项目的时候,如果选择了ESLint,Vue会默认帮我们配置需要的ESLint环境 2、VSCode需要安装ESLint插件 3、解决eslint和prettier冲突的问题
arduino
安装插件:npm install eslint-plugin-prettier eslint-config-prettier -D
如果在创建Vue项目时选择了prettier,那么这两个插件会自动安装 4、添加prettier插件
json
extends: [
'plugin:vue/vue3-essential',
'eslint:recommended',
'@vue/typescript/recommended',
'plugin:prettier/recommended'
],
添加的就是'plugin:prettier/recommended'这一行。
Note:我的实际操作中,保存文件的时候prettier一直没有生效,后来发现是之前安装了Volar插件,某些情况下会接管部分格式化的功能,这时vscode里存在两种格式化的方案。我的处理方式是把prettier设置成默认格式化方式:
- Command+Shift+P调出命令面板,输入format document with......
- 选择配置默认格式化程序
- 选择到prettier
相关截图:


或者可以在 settings.json 的工作区设置中添加如下配置:
json
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
"volar.format.enable": false, // 禁止 Volar 进行格式化
"[vue]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
}