使用 codemod 自动转换 @action 到 slice reducer。

解读

国内主流项目早期普遍使用 mobx 或 dva 等“装饰器风格”状态管理库,代码里大量出现 @action 标记的类方法。随着 Redux Toolkit(RTK) 成为官方推荐,团队需要将存量代码迁移到“slice + createSlice”模式。
面试官问“如何用 codemod 自动把 @action 转成 slice reducer”,核心想验证三点:

  1. 你是否理解 装饰器语法 → 纯函数 reducer 的语义映射;
  2. 能否用 jscodeshift 写出可落地的 AST 转换脚本,而不是人肉替换;
  3. 是否具备 工程化落地经验:批量扫描、白名单、回滚、CI 卡点、灰度策略。
    答不到“AST 怎么写”基本会被判“只看过文档,没写过迁移”。

知识点

  • JavaScript AST:@babel/parser、@babel/traverse、@babel/types 三件套
  • jscodeshift API:find、filter、replaceWith、toSource,以及 collection API 的 chaining 写法
  • 装饰器节点:Decorator > CallExpression > Identifier(name==="action")
  • 类方法节点:ClassMethod,需提取 参数列表 与 函数体,生成 (state, action) => newState 形式的 reducer
  • immer 安全:转换后默认用 RTK 的 immer,所以方法体里 this.xxx = yyy 要改成 state.xxx = yyy 或直接返回新对象
  • 类型系统:若原项目用 TypeScript,需同时生成 PayloadAction<T> 的 类型守卫 与 actionCreator 的 type 常量,否则 TSC 会报错
  • 批量验证:用 eslint-plugin-codemod 在 CI 中做增量检查,防止新代码回退到装饰器风格
  • 灰度策略:按 路由维度 或 业务域 拆分 commit,配合 feature-flag 做线上双写,确保可回滚

答案

  1. 环境准备

    pnpm add -D jscodeshift @babel/parser @babel/traverse @babel/types
    
  2. 脚本核心逻辑(src/codemods/mobx-action-to-slice.js)

    export default function transformer(fileInfo, api) {
      const j = api.jscodeshift;
      const root = j(fileInfo.source);
    
      // 1. 找到所有 @action 装饰的类方法
      const actionMethods = root.find(j.ClassMethod, {
        decorators: path => path.some(d => d.expression.callee && d.expression.callee.name === 'action')
      });
    
      if (actionMethods.length === 0) return fileInfo.source;
    
      const reducers = [];
      const extraReducers = []; // 用于 thunk 或异步
    
      actionMethods.forEach(path => {
        const methodName = path.value.key.name;
        const params = path.value.params.map(p => p.name); // 支持多参数
        const body = path.value.body;
    
        // 2. 把 this.xxx = yyy 转成 state.xxx = yyy
        j(body)
          .find(j.AssignmentExpression, { left: { object: { type: 'ThisExpression' } } })
          .forEach(a => { a.value.left.object = j.identifier('state'); });
    
        // 3. 生成 (state, action) => body
        const reducer = j.arrowFunctionExpression(
          [j.identifier('state'), j.identifier('action')],
          body
        );
    
        reducers.push(
          j.objectProperty(j.identifier(methodName), reducer)
        );
      });
    
      // 4. 构造 createSlice 调用
      const sliceId = fileInfo.path
        .split('/')
        .slice(-2, -1)[0]; // 按目录名当 slice 名
    
      const createSliceCall = j.callExpression(
        j.identifier('createSlice'),
        [
          j.objectExpression([
            j.property('init', j.identifier('name'), j.literal(sliceId)),
            j.property('init', j.identifier('initialState'), j.identifier('initialState')), // 人工补
            j.property('init', j.identifier('reducers'), j.objectExpression(reducers))
          ])
        ]
      );
    
      // 5. 替换整个文件内容为导出语句
      const newSource = j.program([
        j.importDeclaration(
          [j.importSpecifier(j.identifier('createSlice'))],
          j.literal('@reduxjs/toolkit')
        ),
        j.exportDefaultDeclaration(createSliceCall)
      ]);
    
      return j(newSource).toSource({ quote: 'single' });
    }
    
  3. 运行与验证

    npx jscodeshift -t src/codemods/mobx-action-to-slice.js src/stores --extensions=ts,tsx --parser=tsx
    

    随后用 jest 写快照测试,确保转换前后 状态树形状 一致;再用 redux-devtools-diff 比对 100 条录制的用户行为,确认无逻辑差异。

  4. 工程化落地

    • 在 GitLab CI 中加一条 codemod-check job:若 MR 里出现新的 @action,直接失败;
    • 用 husky + lint-staged 做本地拦截,提示开发者“已迁移至 slice,请勿回退”;
    • 上线阶段采用 webpack alias 双Bundle,老模块 StoreLegacy 与新 StoreSlice 并存,通过 LaunchDarkly 按用户灰度 5% → 30% → 100%,可随时回滚。

拓展思考

  • 异步动作如何迁移?@action async fn() 通常对应 createAsyncThunk。可在 codemod 中再扫描 async/await 节点,自动生成
    const fetchXXX = createAsyncThunk('slice/fetchXXX', async (arg) => { ... })
    并在 extraReducers 里补 .addCase(fetchXXX.fulfilled, (state, action) => {...}),实现 “零人工”补全异步模板。
  • 装饰器带参数 @action('rename') 时,需把字符串参数映射为 action type 前缀,避免同名冲突;
  • 多人协作场景下,codemod 脚本要支持 “增量范围” 配置(git diff 列表),防止把兄弟分支的未 Review 代码一并改写;
  • Monorepo 里子包版本不一致,需用 @yarnpkg/core 在脚本里动态解析依赖树,保证转换后 import 路径 指向正确的 @reduxjs/toolkit 版本;
  • 性能兜底:转换后若出现 超大数组 的 state.push(... millions),需提示开发者改用 实体适配器(createEntityAdapter),否则 immer 的 copy-on-write 会造成 毫秒级卡顿;
  • 合规审计:国内金融、政务项目要求 代码变更可溯源,因此 codemod 脚本必须生成 符合《金融科技创新安全规范》 的 commit message 模板,并自动写入 “迁移人+评审人+工单编号”,方便后续稽查。