用于配置 ESLint 规则的配置文件

通常的表现形式有:

  • package.json 中配置 eslintConfig 字段
  • 使用 jsonjavascriptyaml 编写的 .eslintrc.* 文件

有很多信息可以配置:

  • Environments - 指定脚本的运行环境。每种环境都有一组特定的预定义全局变量。
  • Globals - 脚本在执行期间访问的额外的全局变量。
  • Rules - 启用的规则及其各自的错误级别。

例子

一个 .eslintrc 文件示例(使用 json 编写)

1{
2  "extends": "@alexzzz",
3  "rules": {
4    // ...
5  }
6}

eslint 与 prettierrc 使用

安装

  1. vscode搜索插件eslint安装
  2. 控制台运行npx i eslint --init安装并执行eslint初始化
1√ How would you like to use ESLint? · problems # 是否安装
2√ What type of modules does your project use? · esm # es 模块
3√ Which framework does your project use? · vue # vue 框架
4√ Does your project use TypeScript? · Yes # 使用 ts 语法
5√ Where does your code run? · browser, node # 浏览器与 node 环境
6√ What format do you want your config file to be in? · JavaScript # js 文件来配置
7√ Would you like to install them now? · Yes # 安装需要的插件

配置

  • 依赖:npm i @vue/eslint-config-typescript -D.vue 文件的 ts 校验
1// .eslintrc.js
2module.exports = {
3  env: {
4    browser: true,
5    es2021: true,
6    node: true,
7  },
8  extends: [
9    'eslint:recommended', // eslint 推荐规范
10    '@vue/typescript/recommended', // 校验 .vue 文件的 ts,需要安装 npm i @vue/eslint-config-typescript -D
11    'plugin:@typescript-eslint/recommended', // ts 语法插件
12    'plugin:vue/vue3-recommended', // vue3解析 https://eslint.vuejs.org/
13    'plugin:prettier/recommended', // 使 eslint 使用 prettierrc 的规则来校验,避免两者之间的格式冲突,添加到数组的最后一个元素覆盖来去除不必要的规则冲突。
14  ],
15  parserOptions: {
16    ecmaVersion: 'latest',
17    parser: '@typescript-eslint/parser',
18    sourceType: 'module',
19  },
20  plugins: ['vue', '@typescript-eslint'],
21  rules: {
22    'vue/html-self-closing': 'off', // 禁用强制将 <MyComponent></MyComponent> 必须使用 <MyComponent/> 的校验
23    'vue/singleline-html-element-content-newline': 'off',
24    'vue/multi-word-component-names': 'off', // 禁用注册组件 name 不能使用 大写 的报错
25    'vue/prefer-import-from-vue': 'off', // 禁用 import x from '@vue/runtime-dom' 包以 @/ 开头的报错
26    '@typescript-eslint/no-non-null-assertion': 'off', // 允许使用 ts 语法 obj!.a
27    'vue/valid-v-for': 'off', // 禁用 v-for 语法校验, vue3 v-for 不需要绑定 :key,不禁用会报没有绑定 key 的警告
28  },
29  globals: {
30    defineOptions: 'readonly', // unplugin-vue-define-options vite 插件的全局变量
31  },
32}

配置不要做格式校验的文件

根目录.eslintignore

1# 配置不需要做代码格式校验的文件
2node_modules
3dist
4*.css
5*.jpg
6*.jpeg
7*.png
8*.gif
9*.d.ts

代码格式化

  • vscode安装插件Prettier - Code formatter

  • 配置格式化规则

1// .prettierrc.yaml
2singleQuote: false # false 不使用单引号
3semi: false # false 不使用分号
4trailingComma: "es5" # 在多行数组、对象的最后一项添加逗号,单行数组不会添加。
5arrowParens: "avoid" # 箭头函数只有一个参数时省略括号
6endOfLine: "auto" # 结尾自动换行
7singleAttributePerLine: true # true 标签属性使用单行
  • 配置不需要格式化的文件

根目录.prettierignore

1# 配置不需要格式化的文件
2node_modules
3dist

配置prettier格式化与eslint一致

  1. vscode 快捷键 ctrl + , 打开设置
  2. 搜索formatter
  3. Editor:Default Formatter设置为Prettier - Code formatter
  4. 搜索formatter on save打钩,在报存是自动格式化