|
| 1 | +module.exports = (file, api) => { |
| 2 | + const jscodeshift = api.jscodeshift |
| 3 | + const root = jscodeshift(file.source) |
| 4 | + |
| 5 | + const importSpecifiers = root |
| 6 | + .find(jscodeshift.ImportDeclaration, { |
| 7 | + source: { |
| 8 | + value: '@tanstack/react-query', |
| 9 | + }, |
| 10 | + }) |
| 11 | + .find(jscodeshift.ImportSpecifier, { |
| 12 | + imported: { |
| 13 | + name: 'Hydrate', |
| 14 | + }, |
| 15 | + }) |
| 16 | + |
| 17 | + if (importSpecifiers.length > 0) { |
| 18 | + const names = { |
| 19 | + searched: 'Hydrate', // By default, we want to replace the `Hydrate` usages. |
| 20 | + target: 'HydrationBoundary', // We want to replace them with `HydrationBoundary`. |
| 21 | + } |
| 22 | + |
| 23 | + importSpecifiers.replaceWith(({ node: mutableNode }) => { |
| 24 | + /** |
| 25 | + * When the local and imported names match which means the code doesn't contain import aliases, we need |
| 26 | + * to replace only the import specifier. |
| 27 | + * @type {boolean} |
| 28 | + */ |
| 29 | + const usesDefaultImport = |
| 30 | + mutableNode.local.name === mutableNode.imported.name |
| 31 | + |
| 32 | + if (!usesDefaultImport) { |
| 33 | + // If the code uses import aliases, we must re-use the alias. |
| 34 | + names.searched = mutableNode.local.name |
| 35 | + names.target = mutableNode.local.name |
| 36 | + } |
| 37 | + |
| 38 | + // Override the import specifier. |
| 39 | + mutableNode.imported.name = 'HydrationBoundary' |
| 40 | + |
| 41 | + return mutableNode |
| 42 | + }) |
| 43 | + |
| 44 | + root |
| 45 | + .findJSXElements(names.searched) |
| 46 | + .replaceWith(({ node: mutableNode }) => { |
| 47 | + mutableNode.openingElement.name.name = names.target |
| 48 | + mutableNode.closingElement.name.name = names.target |
| 49 | + |
| 50 | + return mutableNode |
| 51 | + }) |
| 52 | + } |
| 53 | + |
| 54 | + return root.toSource({ quote: 'single', lineTerminator: '\n' }) |
| 55 | +} |
0 commit comments