Skip to content

在项目中使用 Eslint

目录

vscode 插件推荐

ESLint 插件

ESLint插件 能够更好的处理规则问题,特殊情况使用快速修复来解决

鼠标移入到标红规则上会出现快速修复 快速修复

点击快速修复会出现以下选项 快速修复选项

  • 单行忽略规则
  • 整个文件忽略规则
  • 查看规则文档

indent-rainbow

indent-rainbow插件

能更好是显示缩进,方便查看代码缩进问题 示例

Prettier - Code formatter

Prettier插件

vscode 配置

.editorconfig 编辑器配置文件

indent_style = space
indent_size = 2
end_of_line = lf

推荐

ctrl + , 打开设置 找到format on save 选择 true 保存时自动格式化

安装依赖

Bash
# 基础安装
# vue2 使用 7.x  vue3使用8.x

# Vue2项目安装
pnpm install eslint@7.14.0 eslint-plugin-vue@6.x babel-eslint@10.1.0 eslint-plugin-prettier@3.4.1 eslint-config-prettier eslint-plugin-import  --save-dev


# Vue3项目安装
pnpm install eslint@8.22.0 eslint-plugin-vue@9.x prettier @vue/eslint-config-prettier eslint-plugin-import --save-dev

#vue3项目使用了typescript
pnpm install @typescript-eslint/parser @typescript-eslint/eslint-plugin --save-dev

初始化 Eslint 文件

vue2

建议跳过此步骤,直接 copy 下面的 .eslintrc.js 文件到项目根目录

Bash
npx eslint --init
# How would you like to use ESLint?
#    如何使用Eslint? --- To check syntax and find problems
# What type of modules does your project use?
#   项目中用的什么模块化配置? --- JavaScript modules (import/export)
# Which framework does your project use?
#   项目用的哪个框架? --- vue
# Does your project use TypeScript?
#   项目是否使用typescript? --- 根据项目选择是否使用typescript
# Where does your code run?
#   运行环境  --- Browser
# What format do you want your config file to be in? · JavaScript
#   配置文件用哪种格式  --- Javascript
javascript
module.exports = {
  env: {
    browser: true,
    es2021: true,
  },
  extends: [
    "eslint:recommended",
    "plugin:vue/essential", // vue2 核心规则
    "plugin:prettier/recommended", //放最后处理eslint和prettire规则冲突
  ],
  parserOptions: {
    ecmaVersion: 12, // es2021
    sourceType: "module",
  },
  plugins: ["vue", "import"],
  rules: {
    "prefer-const": 2,
    "no-const-assign": 2,
    "no-var": 2,
    "no-new-object": 2,
    "object-shorthand": 2,
    "prefer-object-spread": 2,
    "prefer-destructuring": 2,
    "array-callback-return": 2,
    "no-array-constructor": 2,
    "prefer-template": 2,
    "template-curly-spacing": 2,
    "no-eval": 2,
    "wrap-iife": ["error", "inside"],
    "no-loop-func": 2,
    "prefer-rest-params": 2,
    "default-param-last": 2,
    "no-new-func": 2,
    "no-param-reassign": 2,
    "arrow-parens": ["error", "as-needed"],
    "no-duplicate-imports": 2,
    "dot-notation": 2,
    "no-use-before-define": 2,
    "no-unneeded-ternary": 2,
    "brace-style": 2,
    "no-multiple-empty-lines": 2,
    "max-len": ["error", { code: 140 }],
    // 文件最大行数限制
    "max-line": ["error", { 
      "max": 800, 
      // 忽略空行和注释
      "skipBlankLines": true, 
      "skipComments": true }
    ],
    // 函数最大行数限制
    "max-line-per-function":["error", {
      "max": 100,
      "skipBlankLines": true,
      "skipComments": true
    }],
    camelcase: 2,
    "id-length": [
      "error",
      {
        min: 2,
        exceptions: ["e", "i", "j", "k", "a", "b", "x", "y", "z", "_"], // 允许常见单字母变量
      },
    ],
    "import/prefer-default-export": 2,
    "import/no-mutable-exports": "error",
    "import/no-unresolved": "off",
    "import/first": 2,
    "prettier/prettier": [
      "error",
      {
        endOfLine: "auto",
        tabWidth: 2,
        trailingComma: "none",
      },
    ],
  },
};

vue3

出于兼容性考虑 不使用命令初始化配置文件,直接用以下代码

javascript
module.exports = {
  root: true,
  globals: {
    defineProps: "readonly",
    defineEmits: "readonly",
  },
  plugins: ["@typescript-eslint", "import"],
  parserOptions: {
    parser: "@typescript-eslint/parser",
    ecmaVersion: "latest",
    sourceType: "module",
    ecmaFeatures: {
      jsx: true,
    },
  },
  env: {
    browser: true,
    node: true,
    es6: true,
  },
  extends: [
    "plugin:@typescript-eslint/recommended", //ts基础规则
    "plugin:vue/base", //vue基础语法检查
    "plugin:vue/vue3-recommended", //vue3标准语法规则 高强度
    "plugin:import/typescript", //ts模块导入规则
    "plugin:prettier/recommended", //放最后处理eslint和prettire规则冲突
  ],
  rules: {
    "prefer-const": 2,
    "no-const-assign": 2,
    "no-var": 2,
    "no-new-object": 2,
    "object-shorthand": 2,
    "prefer-object-spread": 2,
    "prefer-destructuring": 2,
    "array-callback-return": 2,
    "no-array-constructor": 2,
    "prefer-template": 2,
    "template-curly-spacing": 2,
    "no-eval": 2,
    "wrap-iife": ["error", "inside"],
    "no-loop-func": 2,
    "prefer-rest-params": 2,
    "default-param-last": 2,
    "no-new-func": 2,
    "no-param-reassign": 2,
    "arrow-parens": ["error", "as-needed"],
    "no-duplicate-imports": 2,
    "dot-notation": 2,
    "no-use-before-define": 2,
    "no-unneeded-ternary": 2,
    "brace-style": 2,
    "no-multiple-empty-lines": 2,
    "max-len": ["error", { code: 140 }],
    // 文件最大行数限制
    "max-line": ["error", { 
      "max": 800, 
      // 忽略空行和注释
      "skipBlankLines": true, 
      "skipComments": true }
    ],
    // 函数最大行数限制
    "max-line-per-function":["error", {
      "max": 100,
      "skipBlankLines": true,
      "skipComments": true
    }],
    camelcase: 2,
    "id-length": [
      "error",
      {
        min: 2,
        exceptions: ["e", "i", "j", "k", "v", "a", "b", "_"], // 允许常见单字母变量
      },
    ],
    "import/prefer-default-export": 2,
    "import/no-mutable-exports": "error",
    "import/no-unresolved": "off",
    "import/first": 2,
    "vue/multi-word-component-names": 0,
    "@typescript-eslint/no-non-null-assertion": 0,
    "@typescript-eslint/no-explicit-any": 0,
    "no-duplicate-imports": "off", // 关闭基础规则
    "@typescript-eslint/no-duplicate-imports": ["error"],
    "@typescript-eslint/no-unused-vars": ["error"],
    "vue/no-v-html": "off",
    // Enable vue/script-setup-uses-vars rule
    "prettier/prettier": [
      "error",
      {
        endOfLine: "auto",
        tabWidth: 2,
        trailingComma: "none",
      },
    ],
  },
};

初始化 prettier 文件

不整这些花里胡哨的 直接创建文件最快

javascript
//.prettier  在根目录创建文件
{
  "printWidth": 110,
  // 每行最多字符数,超出换行 eslint需关闭相关规则(如max-len)避免冲突
  "tabWidth": 2,
  //每个缩进两个
  "useTabs": false,
  // 控制缩进使用空格还是tab false:空格, true: tab
  "semi": false,
  // 每句js结尾是否加分号
  "singleQuote": true,
  //是否使用单引号
  "trailingComma": "none",
  // 尾随逗号
  "bracketSpacing": true,
  // 对象括号间距
  "bracketSameLine": true,
   // Vue 3推荐
  "arrowParens": "avoid",
   // 箭头函数括号
  "endOfLine": "lf"
  //行尾风格控制,lf/auto
}

husky 初始化

Bash
# 1. 安装依赖(推荐版本锁定)
pnpm install husky lint-staged --save-dev

# 2. 启用Git钩子
npx husky init

# 3. 自动生成.husky目录结构
├── .husky/
   ├── _/
   ├── pre-commit  # 示例钩子文件

# 4. 配置钩子
# pre-commit文件修改
npx lint-staged

脚本配置

diff
# package.json
{
  "scripts":{
+    "prettier": "prettier --write .",
+    "lint": "eslint . --ext .js,.ts,.vue",
+    "lint:fix": "eslint . --ext .js,.ts,.vue --fix",
+    "lint:style": "stylelint \"src/**/*.{vue,css,scss}\"",
+    "lint:style:fix": "stylelint \"src/**/*.{vue,css,scss}\" --fix"
  },
# husky配置
+  "lint-staged": {
+    "*.{js,ts,vue}": [
+      "eslint --config .eslintrc.js",
+      "prettier --write"
+    ],
+    "*.{css,scss}": [
+      "stylelint --fix"
+    ]
+  },
}

特殊情况需跳过

跳过 hooks 验证

Bash
git commit -m "紧急提交" --no-verify

开始使用

  • step0: 配置好 eslintignore ,stylelintignoreprettierignore文件

  • step1:npm run prettier 进行代码格式化

  • step2:npm run lint 进行代码检查 若出现下图中大量错误,并且提示大部分错误和警告能通过--fix 修复

    *** errors and ** warnings can be fixed by running eslint --fix option.

    可以使用 npm run lint:fix 进行代码修复 示例

  • step3:npm run lint:style 进行样式检查

  • step4:npm run lint:style:fix 进行样式修复

  • step5:git commit -m "chore(lint): fix lint error" 提交代码