列举 Redux 5 的 breaking changes 并给出迁移脚本。

解读

国内一线/二线前端面试中,Redux 版本演进是“必考”环节。Redux 5 于 2023 年 12 月发布,属于主版本号升级,意味着存在运行时行为差异。面试官想验证两点:

  1. 你是否真正踩过升级坑,而不是“背文档”;
  2. 能否给出可落地的迁移脚本,体现工程化思维。
    回答时务必先讲“为什么变”,再给出“怎么改”,并强调国内项目常见的 TypeScript + ESLint + 测试场景。

知识点

  • Redux 5 仅移除已在 v4 标记弃用的 API,无新功能,因此“breaking”集中三点:
    ① 彻底删除 createStore 第二个参数 enhancer 的旧位置写法;
    ② 删除 Store 实例的 replaceReducer 泛型重载;
    ③ 删除 Action 类型上的 any 默认泛型,强制显式声明。
  • 迁移手段:
    1. 代码层:用 legacy_createStore 过渡或直接升级到 Redux Toolkit;
    2. 工具层:ESLint 规则 + jscodeshift 脚本批量替换;
    3. 测试层:跑一遍现有单测,确保状态树形状不变。

答案

  1. createStore 旧 enhancer 位置被移除
    升级前(v4 仍兼容,但控制台已报警):

    const store = createStore(reducer, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());
    

    升级后(v5 直接抛错):

    // ❌ 运行时报错:The preloadedState argument is undefined. You must pass the enhancer as the third argument.
    

    迁移脚本(jscodeshift):

    npx jscodeshift -t scripts/transforms/move-enhancer.js src/ --parser=tsx
    

    move-enhancer.js 核心逻辑:

    export default function transformer(fileInfo, api) {
      const j = api.jscodeshift;
      return j(fileInfo.source)
        .find(j.CallExpression, { callee: { name: 'createStore' } })
        .forEach(path => {
          const [reducer, second, third] = path.value.arguments;
          // 第二个参数是函数且不是 plain object,则判定为 enhancer
          if (second && second.type === 'Identifier' && !third) {
            path.value.arguments = [reducer, j.identifier('undefined'), second];
          }
        })
        .toSource();
    }
    

    改完后再人工复查,推荐一步到位迁移到 Redux Toolkit:

    import { configureStore } from '@reduxjs/toolkit';
    export const store = configureStore({ reducer });
    
  2. Store.replaceReducer 泛型重载被删除
    升级前:

    store.replaceReducer<RootState>(nextRootReducer);
    

    升级后:

    // ❌ TS2554: Expected 1 arguments, but got 2
    

    迁移脚本(TypeScript 编译器 API):

    npx ts-node scripts/remove-replaceReducer-generic.ts
    

    脚本逻辑:遍历所有 .ts/.tsx 文件,把 replaceReducer<...>(...) 改成 replaceReducer(...),并自动格式化。

  3. Action 类型默认泛型被移除
    升级前:

    import { Action } from 'redux';
    const a: Action = { type: 'FOO' }; // v4 默认 any
    

    升级后:

    // ❌ TS2314: Generic type 'Action<T>' requires 1 type argument(s)
    

    迁移脚本(eslint --fix):
    在 .eslintrc.js 新增自定义规则:

    rules: {
      '@typescript-eslint/ban-types': ['error', {
        types: { 'redux/Action': { message: 'Use Action<string> instead', fixWith: 'Action<string>' } }
      }]
    }
    

    执行:

    npm run lint:fix -- --rule '@typescript-eslint/ban-types: ["error"]'
    

一键整体迁移命令(package.json 示范):

"scripts": {
  "redux5:migrate": "npm run redux5:codemod && npm run redux5:ts-fix && npm run test:ci"
}

跑完脚本后,务必全量回归测试;若项目已接入 Redux Toolkit,可直接移除 createStore 相关文件,进一步降低维护成本。

拓展思考

  • 国内微前端场景:qiankun 子应用往往动态注入 reducer,用到 replaceReducer。升级后需确认主、子应用 Redux 版本一致,否则会出现类型撕裂;可在主应用导出统一 Store 类型,子应用通过 declare module 合并类型。
  • 服务端渲染:Next.js 老模板用 createStore 传初始 preloadedState,升级后注意 undefined 占位,避免水合失败。
  • 灰度策略:大仓建议先开 ESLint 错误规则拦截新写法,再配合 monorepo changeset 按业务线分批升级,降低 QA 压力。