Skip to content

Instantly share code, notes, and snippets.

@javascripter
Last active February 25, 2021 21:57
Show Gist options
  • Save javascripter/746b1b1eb76dd088dfb75df0c7e0c8dd to your computer and use it in GitHub Desktop.
Save javascripter/746b1b1eb76dd088dfb75df0c7e0c8dd to your computer and use it in GitHub Desktop.
redux-saga to typed-redux-saga
/*
Description:
This script converts `yield call()` to `yield* call()` syntax and 'redux-saga/effects' to 'typed-redux-saga'
Make sure to commit your files first before you run the below script!
Usage:
npx jscodeshift --parser tsx -t ./migrate-redux-saga.ts ./sagas/**\/*.ts
Before:
import { call, put } from 'redux-saga'
function* runSaga() {
yield call(console.log, 'hello')
yield put({ type: 'RUN_SAGA_SUCCEEDED' })
}
After:
import { call, put } from 'typed-redux-saga'
function* runSaga() {
yield* call(console.log, 'hello')
yield* put({ type: 'RUN_SAGA_SUCCEEDED' })
}
*/
const effectNames = [
'take',
'takeMaybe',
'takeEvery',
'takeLatest',
'takeLeading',
'put',
'putResolve',
'call',
'apply',
'cps',
'fork',
'spawn',
'join',
'cancel',
'select',
'actionChannel',
'flush',
'cancelled',
'setContext',
'getContext',
'delay',
'throttle',
'debounce',
'retry',
'all',
'race',
]
export default (file, api) => {
const j = api.jscodeshift
const root = j(file.source)
// Rewrite all redux-sag/effects imports to typed-redux-saga
root
.find(j.ImportDeclaration, {
source: {
type: 'StringLiteral',
value: 'redux-saga/effects',
},
})
.forEach((path) => {
path.value.source.value = 'typed-redux-saga'
})
// Replace all occurances of yield take, fork, etc. to yield* counterparts
root
.find(j.YieldExpression, {
argument: {
type: 'CallExpression',
callee: {
type: 'Identifier',
name: (name) => effectNames.includes(name),
},
},
})
.forEach((path) => {
path.value.delegate = true
})
return root.toSource({ quote: 'single' })
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment