让你的Vue代码更规范
Reverse Lv4

用到的工具

如果使用的是cursor或者vscode,强烈建议安装以下几个插件:

  • ESLint 代码规范工具
  • Prettier - Code formatter 代码格式化工具
  • Vetur 这是Vue的官方插件,可以提供Vue的语法高亮和智能提示
  • Auto Rename Tag 标签自动闭合
  • TypeScript Vue Plugin 类型提示

配置

首先安装一些依赖,用的上的

1
pnpm add -D eslint prettier eslint-plugin-vue @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint-config-prettier eslint-plugin-prettier

在你的前端项目根目录位置,创建一个.vscode目录,然后创建一个settings.json文件,写入以下内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
{
// 默认使用 VSCode 内置的格式化器(由 ESLint 接管)
"editor.defaultFormatter": "dbaeumer.vscode-eslint",

// 保存时自动修复 + 格式化
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true,
"source.organizeImports": true
},

// Vue 和 TS 文件默认用 ESLint 格式化
"[typescript]": {
"editor.defaultFormatter": "dbaeumer.vscode-eslint"
},
"[typescriptreact]": {
"editor.defaultFormatter": "dbaeumer.vscode-eslint"
},
"[vue]": {
"editor.defaultFormatter": "dbaeumer.vscode-eslint"
},
"[json]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},

// ESLint 插件启用
"eslint.validate": [
"javascript",
"javascriptreact",
"typescript",
"typescriptreact",
"vue"
],

// 关闭 VSCode 自带 TS 报错,用 ESLint 接管
"typescript.validate.enable": false
}

:::warning
这里一定要注意你的.vscode目录是创建在项目根目录下.

并且.prettierrc.json这个文件也是在根目录下,不是在.vscode
:::

然后项目根目录下创建文件.prettierrc.json并且写入以下内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
{
"semi": true, // 语句末尾加分号
"singleQuote": true, // 使用单引号
"trailingComma": "es5", // 尾随逗号,ES5 允许的地方都加(对象、数组等)
"printWidth": 100, // 每行最大长度
"tabWidth": 2, // 缩进 2 空格
"useTabs": false, // 使用空格缩进而不是 tab
"bracketSpacing": true, // { foo: bar } 内部是否留空格
"arrowParens": "always", // 箭头函数参数总是加括号 (x) => x
"endOfLine": "lf", // 换行符(Linux/Mac 推荐 lf)
"vueIndentScriptAndStyle": true, // Vue 文件中 <script> 和 <style> 缩进
"htmlWhitespaceSensitivity": "ignore" // HTML 中空格不敏感
}

完成

到这里就配置完了,然后需要注意的就是,使用编辑器打开项目时必须保证.vscode处于根目录下,否则这些配置不生效.

比如使用工作区打开目录,他应该长这样:

1
2
3
workspace // 这是工作区目录
- .vscode // 这是VSCode的配置目录
- .prettierrc.json // 这是Prettier的配置文件