代码风格检查主要采用eslint+prettier实现,同时由vue-eslint-parser、typescript-eslint、eslint-plugin-import、pretty-quick等扩展其功能。
eslint
用来规定 js 语法的代码风格,同时支持对部分代码风格进行自动格式化
安装依赖
yarn add -D eslint eslint-define-config
添加配置文件
在项目根目录下,创建 .eslintrc.js、.eslintignore文件
.eslintrc.js:该文件为语法检查配置文件
.eslintignore:该文件为语法检查忽略文件(同.gitignore)
添加扩展
由于eslint本身只能对js语法进行检查,为了使其支持其他语言,需添加一些必要的扩展
添加vue支持:yarn add -D eslint-plugin-vue vue-eslint-parser
添加ts支持:yarn add -D @typescript-eslint/eslint-plugin @typescript-eslint/parser
添加import导入检查:yarn add -D eslint-plugin-import
完善配置
.eslintrc.js
const {
defineConfig } = require('eslint-define-config');
// 通过defineConfig声明配置,让配置可以有语法提示
module.exports = defineConfig({
// eslint会逐级向上查找配置文件,直到文件系统根目录,置为true后关闭逐级向上查找
root: true,
// 设置vue-eslint-parser作为vue语法解析器,该解析器应在上层,防止被覆盖
parser: 'vue-eslint-parser',
parserOptions: {
// 此解析器选项由vue-eslint-parser提供,用来设置其他解析器
// 设置@typescript-eslint/parser作为ts语法解析器
parser: '@typescript-eslint/parser',
// 设置项目模块类型为ECMAScript 模块
sourceType: 'module',
// 额外支持jsx,tsx语法
ecmaFeatures: {
jsx: true,
tsx: true,
},
},
// 启用的脚本执行环境
env: {
browser: true,
node: true,
},
// 加载第三方插件,可以配置第三方插件支持的所有规则。可省略eslint-plugin-前缀
plugins: ['@typescript-eslint', 'import'],
// 加载默认规则配置。可省略eslint-config-前缀