|
| 1 | +--- |
| 2 | +id: codemods |
| 3 | +title: Codemods |
| 4 | +sidebar_label: Codemods |
| 5 | +hide_title: true |
| 6 | +--- |
| 7 | + |
| 8 | + |
| 9 | + |
| 10 | +# Codemods |
| 11 | + |
| 12 | +Per [the description in `1.9.0-alpha.0`](https://github.com/reduxjs/redux-toolkit/releases/tag/v1.9.0-alpha.0), we plan to remove the "object" argument from `createReducer` and `createSlice.extraReducers` in the future RTK 2.0 major version. In `1.9.0-alpha.0`, we added a one-shot runtime warning to each of those APIs. |
| 13 | + |
| 14 | +To simplify upgrading codebases, we've published a set of codemods that will automatically transform the deprecated "object" syntax into the equivalent "builder" syntax. |
| 15 | + |
| 16 | +The codemods package is available on NPM as [**`@reduxjs/rtk-codemods`**](https://www.npmjs.com/package/@reduxjs/rtk-codemods). It currently contains two codemods: `createReducerBuilder` and `createSliceBuilder`. |
| 17 | + |
| 18 | +To run the codemods against your codebase, run `npx @reduxjs/rtk-codemods <TRANSFORM NAME> path/of/files/ or/some**/*glob.js`. |
| 19 | + |
| 20 | +Examples: |
| 21 | + |
| 22 | +```bash |
| 23 | +npx @reduxjs/rtk-codemods createReducerBuilder ./src |
| 24 | + |
| 25 | +npx @reduxjs/rtk-codemods createSliceBuilder ./packages/my-app/**/*.ts |
| 26 | +``` |
| 27 | + |
| 28 | +We also recommend re-running Prettier on the codebase before committing the changes. |
| 29 | + |
| 30 | +**These codemods _should_ work, but we would greatly appreciate testing and feedback on more real-world codebases!** |
| 31 | + |
| 32 | +Before: |
| 33 | + |
| 34 | +```js |
| 35 | +createReducer(initialState, { |
| 36 | + [todoAdded1a]: (state, action) => { |
| 37 | + // stuff |
| 38 | + }, |
| 39 | + [todoAdded1b]: (state, action) => action.payload, |
| 40 | +}) |
| 41 | + |
| 42 | +const slice1 = createSlice({ |
| 43 | + name: 'a', |
| 44 | + initialState: {}, |
| 45 | + extraReducers: { |
| 46 | + [todoAdded1a]: (state, action) => { |
| 47 | + // stuff |
| 48 | + }, |
| 49 | + [todoAdded1b]: (state, action) => action.payload, |
| 50 | + }, |
| 51 | +}) |
| 52 | +``` |
| 53 | + |
| 54 | +After: |
| 55 | + |
| 56 | +```js |
| 57 | +createReducer(initialState, (builder) => { |
| 58 | + builder.addCase(todoAdded1a, (state, action) => { |
| 59 | + // stuff |
| 60 | + }) |
| 61 | + |
| 62 | + builder.addCase(todoAdded1b, (state, action) => action.payload) |
| 63 | +}) |
| 64 | + |
| 65 | +const slice1 = createSlice({ |
| 66 | + name: 'a', |
| 67 | + initialState: {}, |
| 68 | + |
| 69 | + extraReducers: (builder) => { |
| 70 | + builder.addCase(todoAdded1a, (state, action) => { |
| 71 | + // stuff |
| 72 | + }) |
| 73 | + |
| 74 | + builder.addCase(todoAdded1b, (state, action) => action.payload) |
| 75 | + }, |
| 76 | +}) |
| 77 | +``` |
0 commit comments