Vuex相关的ESLint规则和最佳实践

解读

国内一线/二线前端面试中,Vue 技术栈占比极高。Vuex 作为官方状态管理方案,其代码质量直接影响大型单页应用的可维护性。面试官抛出“Vuex 相关的 ESLint 规则与最佳实践”,核心意图有三:

  1. 你是否能把“状态管理”与“代码规范”打通,而不仅仅是写业务;
  2. 你是否熟悉社区主流配置(eslint-plugin-vue、@vue/eslint-config-typescript),并能落地到 CI;
  3. 你是否具备“自定义规则”能力,能把团队对 Vuex 的约定(命名、模块拆分、异步流程)固化到工具链,实现“代码即文档”。

回答时必须体现“规则名称 + 配置示例 + 场景价值”,并给出可复制的 .eslintrc.js 片段与国内企业常用的“husky + lint-staged + @commitlint/config-conventional”配套方案。

知识点

  1. 官方插件
    • eslint-plugin-vue:提供 vuex-use-map-state-style、vuex-use-map-helper-style 等 Vuex 专属规则;
    • @typescript-eslint/parser:保证在 TS 项目中识别 .vue 与 store/*.ts 类型。
  2. 核心规则
    • vuex-use-map-state-style:强制使用 mapState 或 useStore(),杜绝 this.$store.state.xxx 硬编码;
    • vuex-use-map-helper-style:统一使用 mapGetters / mapActions / mapMutations,避免重复导入;
    • vuex-no-direct-state-mutation:禁止在组件内直接 store.state.count = 1,保证单向数据流;
    • vuex-no-unnecessary-action:若 action 内仅做同步提交,则提示用 mutation 代替;
    • vuex-prefer-separate-files:当 store 目录下单一文件超过 300 行时警告,推动模块化;
    • no-shadow + no-param-reassign:解决 state.xxx = payload 被误报问题,需配置 ignorePropertyModificationsFor: ['state']。
  3. 命名约定
    • 模块文件:user.store.ts、product.store.ts;
    • mutation:常量 USER_SET_NAME、函数 SET_USER_NAME;
    • action:异步以 fetch/load 开头,如 fetchUserProfile;
    • getter:以 get/is/filtered 开头,如 getUserById。
  4. 异步流程
    • 推荐 async/await + try/catch,action 返回 Promise;
    • 禁止在组件内 this.$store.dispatch(...).then(...) 链式回调,统一在 action 内处理副作用,组件只 await 结果。
  5. 配套工具链
    • husky:pre-commit 触发 lint-staged;
    • lint-staged:仅校验本次提交涉及的 .vue/.ts 文件;
    • @commitlint/config-conventional:提交信息若含 feat(vuex) 前缀,CI 自动跑 npm run lint:vuex;
    • vite-plugin-eslint:开发阶段即时反馈,减少构建后才发现问题。

答案

“我们在日均百万 PV 的电商后台中,把 Vuex 规范拆成三层:语法层、风格层、架构层,全部落到 ESLint。

  1. 语法层——直接引用官方规则 .eslintrc.js 关键片段:

    module.exports = {
      root: true,
      parser: 'vue-eslint-parser',
      parserOptions {
        parser: '@typescript-eslint/parser',
        ecmaVersion: 2022,
        sourceType: 'module',
        project: './tsconfig.json'
      },
      plugins: ['vue', '@typescript-eslint'],
      extends: [
        '@vue/typescript/recommended',
        'plugin:vue/vue3-recommended',
        'plugin:vuex/recommended' // 新增
      ],
      rules: {
        'vuex/use-map-state-style': ['error', 'always'],
        'vuex/use-map-helper-style': 'error',
        'vuex/no-direct-state-mutation': 'error',
        'vuex/no-unnecessary-action': 'warn',
        'vuex/prefer-separate-files': ['warn', { maxLines: 300 }],
        'no-shadow': 'off',
        '@typescript-eslint/no-shadow': 'error',
        'no-param-reassign': ['error', { props: true, ignorePropertyModificationsFor: ['state', 'acc'] }]
      }
    };
    

    效果:CI 流水线中若出现 this.$store.state.cartList.push(x),会直接失败,强制开发者用 mapState 或 useStore()。

  2. 风格层——自定义命名规则 由于官方插件未覆盖命名,我们基于 eslint-rule-composer 写了一个内部规则 vuex-module-naming,核心逻辑:

    • 文件必须匹配 *.store.ts;
    • mutation 常量必须全大写 + 下划线;
    • action 必须返回 Promise 且以 fetch/load/update 开头。 规则部署在私有 @abc/eslint-plugin-abc,版本锁定后发布到内网 Verdaccio,所有项目 extends: plugin:abc/vuex 一键继承。
  3. 架构层——大文件检测与模块化 当单文件超过 300 行,vuex/prefer-separate-files 提示拆分为 store/modules/user.ts + store/modules/user.types.ts。配合 vuex-module-decorators 时,要求每个 module 单独导出接口,方便其他模块复用类型。

  4. Git 工作流 package.json 脚本:

    "lint:vuex": "eslint --ext .vue,.ts src/store",
    "lint:vuex:fix": "npm run lint:vuex -- --fix"
    

    .husky/pre-commit:

    #!/bin/sh
    . "$(dirname "$0")/_/husky.sh"
    npx lint-staged
    

    lint-staged.config.js:

    module.exports = {
      '*.{vue,ts}': ['eslint --fix', 'git add'],
      'src/store/**/*': 'npm run lint:vuex:fix'
    };
    

    如此保证任何一次提交,store 目录代码 100% 通过 ESLint,无需人工 review 低级错误。

  5. 落地收益 上线三个月,store 相关 Bug 下降 42%,Code Review 耗时人均减少 18 分钟/PR,新同学上手时间从 3 天缩短到 0.5 天。”

拓展思考

  1. Pinia 迁移场景 未来 Vue3 项目逐步迁移 Pinia 时,可复用同一套“自定义命名”思路,开发 pinia/use-setup-store-style、pinia/no-direct-state-mutation 等规则,实现 ESLint 层面对 Pinia 的同等约束,降低迁移回退风险。
  2. 性能规则 对巨型列表场景,可新增自定义规则 vuex-no-big-list-in-state,当检测到 state.list = Array(5000) 以上量级时给出警告,提示使用分页索引或 IndexedDB,避免 Vue 响应式劫持导致初始化卡顿。
  3. 微前端冲突 在 qiankun 微前端方案中,多个子应用共享运行时,可能出现模块名冲突。可扩展 vuex-module-naming 规则,要求模块名以“子应用前缀”开头,如 app1_user,并在 CI 阶段通过 eslint --rule 'vuex-module-naming: [error, { prefix: app1 }]' 动态注入,保证主应用聚合时无命名污染。
  4. 自动化文档 结合 eslint-plugin-jsdoc 与自定义规则,强制每个 mutation、action 书写 @param 与 @returns,再通过脚本自动生成 store-docs.md 并上传到内部语雀,实现“代码改动 → 文档更新”无人值守。