代码规范自动检查(VUE3+ESlint+Prettier )

1,572 阅读2分钟

代码规范自动检查

项目依赖下载

依赖下载

需要下载五个依赖命令如下:

 npm i -D prettier eslint eslint-plugin-vue @vue/eslint-config-prettier @vue/eslint-config-typescript 
  • Prettier 的作用是格式化代码风格,后续加上 VS Code 的 Prettier 插件,可以在保存代码时候,自动格式化代码风格。
  • eslint 是 ESLint 的核心模块,包括 CLI 命令工具;
  • eslint-plugin-vue 是 ESLint 的 Vue.js 语法插件,主要用于检查 Vue 代码文件语法;
  • @vue/eslint-config-prettier 是 ESLint 的 Prettier 配置,主要是联动 Prettier 进行代码规范的格式化;
  • @vue/eslint-config-typescript 是 ESLint 的 TypeScript 配置,主要是检查 Vue.js 项目中的 TypeScript 语法;

设置 ESLint 项目配置文件

在项目根目录下新建文件,命名为.eslintrc.cjs

配置参考:

 /* eslint-env node */ //此行注释为屏蔽Eslint检查
 ​
 module.exports = {
   root: true,
   plugins: ['prettier'],
   extends: [
     'plugin:vue/vue3-essential',
     'plugin:prettier/recommended',
     'eslint:recommended',
     '@vue/eslint-config-typescript/recommended',
     '@vue/eslint-config-prettier'
   ],
   rules: {
     // 单引号限制
     quotes: ['error', 'single'],
     // 禁用console
     'no-console': 'error'
   }
 };
 ​

更多配置查看ESlint官方文档

设置 Prettier项目配置文件

在根目录创建 prettier 配置文件 .prettierrc.json

参考配置:

 /* eslint-env node */
 {
   "tabWidth": 2,
   "useTabs": false,
   "endOfLine": "auto",
   "singleQuote": true,
   "semi": true,
   "trailingComma": "none",
   "bracketSpacing": true
 }

这些配置主要是代码风格的配置,更多配置信息可以查看官方文档

vscode 插件下载

需要下载5个插件:

  • Vue.volar : Vue 3 官方推荐的 VS Code 开发插件;
  • Vue.vscode-typescript-vue-plugin: Vue 3 TypeScript 语法辅助 VS Code 插件;
  • dbaeumer.vscode-eslint : ESLint 的 VS Code 插件;
  • esbenp.prettier-vscode :Prettier 的 VS Code 插件;
  • rvest.vs-code-prettier-eslint:ESLint 联动 Prettier 的 VS Code 插件;

配置 VS Code 的项目本地配置文件 .vscode/settings.json

打开本地配置文件 .vscode/settings.json,添加如下配置:

   "editor.formatOnSave": true,
   "eslint.format.enable": true,
   "prettier.configPath": ".prettierrc.json",
   "[typescript]": {
     "editor.defaultFormatter": "esbenp.prettier-vscode"
   },
   "[typescriptreact]": {
     "editor.defaultFormatter": "esbenp.prettier-vscode"
   },
   "[vue]": {
     "editor.defaultFormatter": "esbenp.prettier-vscode"
   }

用 ESLint 检查代码质量

在 package.json 里配置 ESLint 的 CLI 使用脚本:

 {
   "scripts": {
     "lint": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts --fix --ignore-path .gitignore"
   }
 }

在控制台输入如下命令,即可按照配置的规则检查代码质量

 npm run lint

团队协同

在项目的根目录下创建一个 .vscode 的目录。接着再创建 VS Code 扩展插件的配置文件 .vscode/extensions.json,声明需要用到的插件,这样子只要用 VS Code 打开这个项目,就可以提醒团队成员去安装相关插件了。

 {
   "recommendations": [
     "Vue.volar",
     "Vue.vscode-typescript-vue-plugin",
     "rvest.vs-code-prettier-eslint",
     "dbaeumer.vscode-eslint",
     "esbenp.prettier-vscode"
   ]
 }