跳至主要內容

eslintrc

h7mlengineeringeslint大约 3 分钟约 769 字

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

通常的表现形式有:

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

有很多信息可以配置:

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

例子

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

{
  "extends": "@alexzzz",
  "rules": {
    // ...
  }
}

eslint 与 prettierrc 使用

安装

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

配置

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

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

根目录.eslintignore

# 配置不需要做代码格式校验的文件
node_modules
dist
*.css
*.jpg
*.jpeg
*.png
*.gif
*.d.ts

代码格式化

  • vscode安装插件Prettier - Code formatter

  • 配置格式化规则

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

根目录.prettierignore

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

配置prettier格式化与eslint一致

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