ESLint 和 prettier 配置 小记

305 阅读1分钟
1、安装依赖
//eslint 安装
yarn add eslint -D

//eslint vue插件安装
yarn add eslint-plugin-vue -D

//eslint 识别ts语法
yarn add @typescript-eslint/parser -D

//eslint ts默认规则补充
yarn add @typescript-eslint/eslint-plugin -D

//eslint prettier插件安装
yarn add eslint-plugin-prettier -D

//用来解决与eslint的冲突
yarn add eslint-config-prettier -D 

//安装prettier
yarn add prettier -D


2. 新建 .eslintrc
{
  "env": {
    "browser": true,
    "node": true,
    "es2021": true
  },
  "parser": "vue-eslint-parser",
  "extends": [
    "eslint:recommended",
    "plugin:vue/vue3-recommended",
    "plugin:@typescript-eslint/recommended",
    "plugin:prettier/recommended",
    "eslint-config-prettier"
  ],
  "parserOptions": {
    "ecmaVersion": "latest",
    "parser": "@typescript-eslint/parser",
    "sourceType": "module",
    "ecmaFeatures": {
      "jsx": true
    }
  },
  "plugins": ["vue", "@typescript-eslint", "prettier"],
  "rules": {
    "vue/multi-word-component-names": "off", // 禁用vue文件强制多个单词命名
    "@typescript-eslint/no-explicit-any": ["off"], //允许使用any
    "@typescript-eslint/no-this-alias": [
      "error",
      {
        "allowedNames": ["that"] // this可用的局部变量名称
      }
    ],
    "@typescript-eslint/ban-ts-comment": "off", //允许使用@ts-ignore
    "@typescript-eslint/no-non-null-assertion": "off", //允许使用非空断言
    "no-console": [
      //提交时不允许有console.log
      "warn",
      {
        "allow": ["warn", "error"]
      }
    ],
    "no-debugger": "warn" //提交时不允许有debugger
  }
}

[更过配置](Rules Reference - ESLint - Pluggable JavaScript Linter)

3、新建 .eslintignore
# eslint 忽略检查 (根据项目需要自行添加)
node_modules
dist


4、 新建 .prettierrc

{
    "endOfLine": "auto",
    "printWidth": 120,
    "semi": true,
    "singleQuote": true,
    "tabWidth": 2,
    "trailingComma": "all",
    "bracketSpacing": true
}

5、 新建 .prettierignore
# 忽略格式化文件 (根据项目需要自行添加)
node_modules
dist

6、重启vscode使配置生效
7、配置package.json
"scripts": {
    "lint": "eslint src --fix --ext .ts,.tsx,.vue,.js,.jsx --max-warnings 0"
},

运行 yarn run lint,可以看到上述eslint(prettier/prettier)问题都将被修复

vscode 保存自动格式化

在.vscode下新建 settings.json

{
  "editor.codeActionsOnSave": {
    "source.fixAll": true
  }
}

之后每次文件有修改,保存时,都会自动格式化