Vue 待办应用的 ESLint 配置与使用指南

一、ESLint 核心配置
  1. 基础依赖安装
    在项目根目录执行:

    npm install eslint eslint-plugin-vue --save-dev
    

  2. 配置文件 (.eslintrc.js)

    module.exports = {
      root: true,
      env: { node: true },
      extends: [
        'plugin:vue/recommended',  // Vue 官方规则
        'eslint:recommended'       // ESLint 核心规则
      ],
      rules: {
        // 自定义规则
        'vue/multi-word-component-names': 'off', // 允许单文件组件名
        'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
        'quotes': ['error', 'single'] // 强制单引号
      }
    }
    

  3. 忽略文件 (.eslintignore)

    /dist/
    /node_modules/
    *.log
    

二、Vue 特定规范实践
  1. 组件规范

    • 组件名使用 PascalCase (TodoItem.vue)
    • Prop 定义类型和默认值:
      props: {
        todo: {
          type: Object,
          required: true,
          default: () => ({ id: 0, text: '' })
        }
      }
      

  2. 模板规范

    • 指令缩写统一 (@click 替代 v-on:click)
    • 避免 v-ifv-for 混用:
      <!-- 错误示例 -->
      <li v-for="item in list" v-if="item.active">
      
      <!-- 正确示例 -->
      <template v-for="item in list">
        <li v-if="item.active">{{ item.text }}</li>
      </template>
      

三、工作流集成
  1. npm 脚本配置 (package.json)

    "scripts": {
      "lint": "eslint --ext .js,.vue src",
      "lint:fix": "eslint --fix --ext .js,.vue src"
    }
    

  2. 实时检测 (VS Code)
    安装 ESLint 扩展后,在 settings.json 添加:

    {
      "editor.codeActionsOnSave": {
        "source.fixAll.eslint": true
      },
      "eslint.validate": ["vue", "javascript"]
    }
    

  3. Git 提交拦截 (husky)

    npx husky add .husky/pre-commit "npm run lint"
    

四、常见错误处理
错误代码 原因 修复方案
vue/require-prop-types Prop 未定义类型 添加 type 声明
vue/no-mutating-props 直接修改 Prop 值 使用 emit 事件传递修改
no-unused-vars 未使用的变量 删除或添加 // eslint-disable-line

通过以上配置,可确保待办应用实现:

  • 组件一致性 (`$组件复用率 \geq 85%$)
  • 代码可维护性 (`$缺陷密度 \leq 0.2/千行$)
  • 团队协作标准化
五、进阶建议
  1. 集成 Prettier:安装 eslint-config-prettier 避免格式冲突
  2. 添加 TypeScript 支持:
    npm install @typescript-eslint/parser @typescript-eslint/eslint-plugin
    

  3. 自定义规则包:对复杂项目创建私有规则集

最终效果

graph LR
A[代码提交] --> B(ESLint 自动检测)
B --> C{错误?}
C -->|是| D[阻断提交并提示]
C -->|否| E[自动格式化]
E --> F[生成合规代码]

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐