@openrewrite/recipes-react 0.14.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (238) hide show
  1. package/dist/index.d.ts +12 -4
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +70 -17
  4. package/dist/index.js.map +1 -1
  5. package/dist/migration/cra-to-vite/add-vite-config.d.ts +9 -0
  6. package/dist/migration/cra-to-vite/add-vite-config.d.ts.map +1 -0
  7. package/dist/migration/cra-to-vite/add-vite-config.js +49 -0
  8. package/dist/migration/cra-to-vite/add-vite-config.js.map +1 -0
  9. package/dist/migration/cra-to-vite/cra-blockers-table.d.ts +10 -0
  10. package/dist/migration/cra-to-vite/cra-blockers-table.d.ts.map +1 -0
  11. package/dist/migration/cra-to-vite/cra-blockers-table.js +31 -0
  12. package/dist/migration/cra-to-vite/cra-blockers-table.js.map +1 -0
  13. package/dist/migration/cra-to-vite/cra-to-vite.d.ts +14 -0
  14. package/dist/migration/cra-to-vite/cra-to-vite.d.ts.map +1 -0
  15. package/dist/migration/cra-to-vite/cra-to-vite.js +73 -0
  16. package/dist/migration/cra-to-vite/cra-to-vite.js.map +1 -0
  17. package/dist/migration/cra-to-vite/find-cra-config-blockers.d.ts +14 -0
  18. package/dist/migration/cra-to-vite/find-cra-config-blockers.d.ts.map +1 -0
  19. package/dist/migration/cra-to-vite/find-cra-config-blockers.js +177 -0
  20. package/dist/migration/cra-to-vite/find-cra-config-blockers.js.map +1 -0
  21. package/dist/migration/cra-to-vite/find-cra-env-file-blockers.d.ts +10 -0
  22. package/dist/migration/cra-to-vite/find-cra-env-file-blockers.d.ts.map +1 -0
  23. package/dist/migration/cra-to-vite/find-cra-env-file-blockers.js +67 -0
  24. package/dist/migration/cra-to-vite/find-cra-env-file-blockers.js.map +1 -0
  25. package/dist/migration/cra-to-vite/find-cra-source-blockers.d.ts +10 -0
  26. package/dist/migration/cra-to-vite/find-cra-source-blockers.d.ts.map +1 -0
  27. package/dist/migration/cra-to-vite/find-cra-source-blockers.js +168 -0
  28. package/dist/migration/cra-to-vite/find-cra-source-blockers.js.map +1 -0
  29. package/dist/migration/cra-to-vite/find-cra-to-vite-blockers.d.ts +8 -0
  30. package/dist/migration/cra-to-vite/find-cra-to-vite-blockers.d.ts.map +1 -0
  31. package/dist/migration/cra-to-vite/find-cra-to-vite-blockers.js +31 -0
  32. package/dist/migration/cra-to-vite/find-cra-to-vite-blockers.js.map +1 -0
  33. package/dist/migration/cra-to-vite/index.d.ts +16 -0
  34. package/dist/migration/cra-to-vite/index.d.ts.map +1 -0
  35. package/dist/migration/cra-to-vite/index.js +35 -0
  36. package/dist/migration/cra-to-vite/index.js.map +1 -0
  37. package/dist/migration/cra-to-vite/move-public-index-html.d.ts +11 -0
  38. package/dist/migration/cra-to-vite/move-public-index-html.d.ts.map +1 -0
  39. package/dist/migration/cra-to-vite/move-public-index-html.js +124 -0
  40. package/dist/migration/cra-to-vite/move-public-index-html.js.map +1 -0
  41. package/dist/migration/cra-to-vite/rename-process-env-react-app.d.ts +9 -0
  42. package/dist/migration/cra-to-vite/rename-process-env-react-app.d.ts.map +1 -0
  43. package/dist/migration/cra-to-vite/rename-process-env-react-app.js +92 -0
  44. package/dist/migration/cra-to-vite/rename-process-env-react-app.js.map +1 -0
  45. package/dist/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.d.ts +9 -0
  46. package/dist/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.d.ts.map +1 -0
  47. package/dist/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.js +65 -0
  48. package/dist/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.js.map +1 -0
  49. package/dist/migration/cra-to-vite/replace-react-scripts-dependency.d.ts +14 -0
  50. package/dist/migration/cra-to-vite/replace-react-scripts-dependency.d.ts.map +1 -0
  51. package/dist/migration/cra-to-vite/replace-react-scripts-dependency.js +78 -0
  52. package/dist/migration/cra-to-vite/replace-react-scripts-dependency.js.map +1 -0
  53. package/dist/migration/cra-to-vite/scan-cra-projects.d.ts +21 -0
  54. package/dist/migration/cra-to-vite/scan-cra-projects.d.ts.map +1 -0
  55. package/dist/migration/cra-to-vite/scan-cra-projects.js +87 -0
  56. package/dist/migration/cra-to-vite/scan-cra-projects.js.map +1 -0
  57. package/dist/migration/cra-to-vite/shared.d.ts +24 -0
  58. package/dist/migration/cra-to-vite/shared.d.ts.map +1 -0
  59. package/dist/migration/cra-to-vite/shared.js +105 -0
  60. package/dist/migration/cra-to-vite/shared.js.map +1 -0
  61. package/dist/migration/cra-to-vite/update-react-app-env-types.d.ts +9 -0
  62. package/dist/migration/cra-to-vite/update-react-app-env-types.d.ts.map +1 -0
  63. package/dist/migration/cra-to-vite/update-react-app-env-types.js +47 -0
  64. package/dist/migration/cra-to-vite/update-react-app-env-types.js.map +1 -0
  65. package/dist/migration/cra-to-vite/update-react-scripts-scripts.d.ts +9 -0
  66. package/dist/migration/cra-to-vite/update-react-scripts-scripts.d.ts.map +1 -0
  67. package/dist/migration/cra-to-vite/update-react-scripts-scripts.js +62 -0
  68. package/dist/migration/cra-to-vite/update-react-scripts-scripts.js.map +1 -0
  69. package/dist/migration/cra-to-vite/update-tsconfig-for-vite.d.ts +10 -0
  70. package/dist/migration/cra-to-vite/update-tsconfig-for-vite.d.ts.map +1 -0
  71. package/dist/migration/cra-to-vite/update-tsconfig-for-vite.js +44 -0
  72. package/dist/migration/cra-to-vite/update-tsconfig-for-vite.js.map +1 -0
  73. package/dist/react17/migrate-deprecated-lifecycles.d.ts +8 -0
  74. package/dist/react17/migrate-deprecated-lifecycles.d.ts.map +1 -0
  75. package/dist/react17/migrate-deprecated-lifecycles.js +258 -0
  76. package/dist/react17/migrate-deprecated-lifecycles.js.map +1 -0
  77. package/dist/react17/use-new-jsx-transform.d.ts +8 -0
  78. package/dist/react17/use-new-jsx-transform.d.ts.map +1 -0
  79. package/dist/react17/use-new-jsx-transform.js +121 -0
  80. package/dist/react17/use-new-jsx-transform.js.map +1 -0
  81. package/dist/react18/add-children-to-props.d.ts +8 -0
  82. package/dist/react18/add-children-to-props.d.ts.map +1 -0
  83. package/dist/react18/add-children-to-props.js +277 -0
  84. package/dist/react18/add-children-to-props.js.map +1 -0
  85. package/dist/react18/replace-reactdom-render.d.ts.map +1 -1
  86. package/dist/react18/replace-reactdom-render.js +109 -12
  87. package/dist/react18/replace-reactdom-render.js.map +1 -1
  88. package/dist/react18/replace-unmount-component-at-node.d.ts.map +1 -1
  89. package/dist/react18/replace-unmount-component-at-node.js +62 -20
  90. package/dist/react18/replace-unmount-component-at-node.js.map +1 -1
  91. package/dist/react19/replace-default-props.d.ts.map +1 -1
  92. package/dist/react19/replace-default-props.js +10 -13
  93. package/dist/react19/replace-default-props.js.map +1 -1
  94. package/dist/react19/replace-react-shallow-renderer.d.ts.map +1 -1
  95. package/dist/react19/replace-react-shallow-renderer.js +1 -6
  96. package/dist/react19/replace-react-shallow-renderer.js.map +1 -1
  97. package/dist/refactoring/class-to-functional.d.ts.map +1 -1
  98. package/dist/refactoring/class-to-functional.js +81 -7
  99. package/dist/refactoring/class-to-functional.js.map +1 -1
  100. package/dist/refactoring/create-class-to-es6.d.ts.map +1 -1
  101. package/dist/refactoring/create-class-to-es6.js +4 -7
  102. package/dist/refactoring/create-class-to-es6.js.map +1 -1
  103. package/dist/refactoring/create-element-to-jsx.d.ts.map +1 -1
  104. package/dist/refactoring/create-element-to-jsx.js +3 -4
  105. package/dist/refactoring/create-element-to-jsx.js.map +1 -1
  106. package/dist/refactoring/fix-async-effect.d.ts +8 -0
  107. package/dist/refactoring/fix-async-effect.d.ts.map +1 -0
  108. package/dist/refactoring/fix-async-effect.js +71 -0
  109. package/dist/refactoring/fix-async-effect.js.map +1 -0
  110. package/dist/refactoring/prop-types-to-typescript.d.ts +8 -0
  111. package/dist/refactoring/prop-types-to-typescript.d.ts.map +1 -0
  112. package/dist/refactoring/prop-types-to-typescript.js +341 -0
  113. package/dist/refactoring/prop-types-to-typescript.js.map +1 -0
  114. package/dist/refactoring/pure-render-mixin.d.ts.map +1 -1
  115. package/dist/refactoring/pure-render-mixin.js +3 -6
  116. package/dist/refactoring/pure-render-mixin.js.map +1 -1
  117. package/dist/search/find-deprecated-lifecycles.d.ts +12 -0
  118. package/dist/search/find-deprecated-lifecycles.d.ts.map +1 -0
  119. package/dist/search/find-deprecated-lifecycles.js +86 -0
  120. package/dist/search/find-deprecated-lifecycles.js.map +1 -0
  121. package/dist/search/find-effects-without-cleanup.d.ts +9 -0
  122. package/dist/search/find-effects-without-cleanup.d.ts.map +1 -0
  123. package/dist/search/find-effects-without-cleanup.js +133 -0
  124. package/dist/search/find-effects-without-cleanup.js.map +1 -0
  125. package/dist/search/find-enzyme-usage.d.ts +9 -0
  126. package/dist/search/find-enzyme-usage.d.ts.map +1 -0
  127. package/dist/search/find-enzyme-usage.js +155 -0
  128. package/dist/search/find-enzyme-usage.js.map +1 -0
  129. package/dist/search/find-function-component-default-props.d.ts +11 -0
  130. package/dist/search/find-function-component-default-props.d.ts.map +1 -0
  131. package/dist/search/find-function-component-default-props.js +96 -0
  132. package/dist/search/find-function-component-default-props.js.map +1 -0
  133. package/dist/search/find-legacy-react-apis.d.ts +8 -0
  134. package/dist/search/find-legacy-react-apis.d.ts.map +1 -0
  135. package/dist/search/find-legacy-react-apis.js +41 -0
  136. package/dist/search/find-legacy-react-apis.js.map +1 -0
  137. package/dist/search/find-missing-use-client-directive.d.ts +9 -0
  138. package/dist/search/find-missing-use-client-directive.d.ts.map +1 -0
  139. package/dist/search/find-missing-use-client-directive.js +127 -0
  140. package/dist/search/find-missing-use-client-directive.js.map +1 -0
  141. package/dist/search/find-reactdom-root-apis.d.ts +14 -0
  142. package/dist/search/find-reactdom-root-apis.d.ts.map +1 -0
  143. package/dist/search/find-reactdom-root-apis.js +122 -0
  144. package/dist/search/find-reactdom-root-apis.js.map +1 -0
  145. package/dist/testing/enzyme-host-components.d.ts +14 -0
  146. package/dist/testing/enzyme-host-components.d.ts.map +1 -0
  147. package/dist/testing/enzyme-host-components.js +245 -0
  148. package/dist/testing/enzyme-host-components.js.map +1 -0
  149. package/dist/testing/enzyme-to-react-testing-library.d.ts +41 -0
  150. package/dist/testing/enzyme-to-react-testing-library.d.ts.map +1 -0
  151. package/dist/testing/enzyme-to-react-testing-library.js +572 -0
  152. package/dist/testing/enzyme-to-react-testing-library.js.map +1 -0
  153. package/dist/testing/enzyme-usage.d.ts +22 -0
  154. package/dist/testing/enzyme-usage.d.ts.map +1 -0
  155. package/dist/testing/enzyme-usage.js +107 -0
  156. package/dist/testing/enzyme-usage.js.map +1 -0
  157. package/dist/testing/enzyme-wrapper-scope.d.ts +51 -0
  158. package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -0
  159. package/dist/testing/enzyme-wrapper-scope.js +420 -0
  160. package/dist/testing/enzyme-wrapper-scope.js.map +1 -0
  161. package/dist/util/module-imports.d.ts +12 -0
  162. package/dist/util/module-imports.d.ts.map +1 -0
  163. package/dist/util/module-imports.js +56 -0
  164. package/dist/util/module-imports.js.map +1 -0
  165. package/dist/util/react-class.d.ts +7 -0
  166. package/dist/util/react-class.d.ts.map +1 -0
  167. package/dist/util/react-class.js +42 -0
  168. package/dist/util/react-class.js.map +1 -0
  169. package/dist/util/tree-search.d.ts +6 -0
  170. package/dist/util/tree-search.d.ts.map +1 -0
  171. package/dist/util/tree-search.js +51 -0
  172. package/dist/util/tree-search.js.map +1 -0
  173. package/package.json +7 -4
  174. package/src/index.ts +53 -12
  175. package/src/migration/cra-to-vite/add-vite-config.ts +47 -0
  176. package/src/migration/cra-to-vite/cra-blockers-table.ts +27 -0
  177. package/src/migration/cra-to-vite/cra-to-vite.ts +76 -0
  178. package/src/migration/cra-to-vite/find-cra-config-blockers.ts +173 -0
  179. package/src/migration/cra-to-vite/find-cra-env-file-blockers.ts +60 -0
  180. package/src/migration/cra-to-vite/find-cra-source-blockers.ts +138 -0
  181. package/src/migration/cra-to-vite/find-cra-to-vite-blockers.ts +21 -0
  182. package/src/migration/cra-to-vite/index.ts +26 -0
  183. package/src/migration/cra-to-vite/move-public-index-html.ts +132 -0
  184. package/src/migration/cra-to-vite/rename-process-env-react-app.ts +93 -0
  185. package/src/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.ts +61 -0
  186. package/src/migration/cra-to-vite/replace-react-scripts-dependency.ts +71 -0
  187. package/src/migration/cra-to-vite/scan-cra-projects.ts +86 -0
  188. package/src/migration/cra-to-vite/shared.ts +123 -0
  189. package/src/migration/cra-to-vite/update-react-app-env-types.ts +40 -0
  190. package/src/migration/cra-to-vite/update-react-scripts-scripts.ts +64 -0
  191. package/src/migration/cra-to-vite/update-tsconfig-for-vite.ts +40 -0
  192. package/src/react17/migrate-deprecated-lifecycles.ts +265 -0
  193. package/src/react17/use-new-jsx-transform.ts +108 -0
  194. package/src/react18/add-children-to-props.ts +235 -0
  195. package/src/react18/replace-reactdom-render.ts +109 -20
  196. package/src/react18/replace-unmount-component-at-node.ts +78 -32
  197. package/src/react19/replace-default-props.ts +11 -15
  198. package/src/react19/replace-react-shallow-renderer.ts +2 -7
  199. package/src/refactoring/class-to-functional.ts +101 -13
  200. package/src/refactoring/create-class-to-es6.ts +6 -9
  201. package/src/refactoring/create-element-to-jsx.ts +4 -6
  202. package/src/refactoring/fix-async-effect.ts +88 -0
  203. package/src/refactoring/prop-types-to-typescript.ts +341 -0
  204. package/src/refactoring/pure-render-mixin.ts +4 -7
  205. package/src/search/find-deprecated-lifecycles.ts +64 -0
  206. package/src/search/find-effects-without-cleanup.ts +109 -0
  207. package/src/search/find-enzyme-usage.ts +117 -0
  208. package/src/search/find-function-component-default-props.ts +68 -0
  209. package/src/search/find-legacy-react-apis.ts +41 -0
  210. package/src/search/find-missing-use-client-directive.ts +99 -0
  211. package/src/search/find-reactdom-root-apis.ts +99 -0
  212. package/src/testing/enzyme-host-components.ts +283 -0
  213. package/src/testing/enzyme-to-react-testing-library.ts +622 -0
  214. package/src/testing/enzyme-usage.ts +94 -0
  215. package/src/testing/enzyme-wrapper-scope.ts +456 -0
  216. package/src/util/module-imports.ts +55 -0
  217. package/src/util/react-class.ts +35 -0
  218. package/src/util/tree-search.ts +32 -0
  219. package/dist/react16/upgrade-to-react-16.d.ts +0 -12
  220. package/dist/react16/upgrade-to-react-16.d.ts.map +0 -1
  221. package/dist/react16/upgrade-to-react-16.js +0 -66
  222. package/dist/react16/upgrade-to-react-16.js.map +0 -1
  223. package/dist/react17/upgrade-to-react-17.d.ts +0 -12
  224. package/dist/react17/upgrade-to-react-17.d.ts.map +0 -1
  225. package/dist/react17/upgrade-to-react-17.js +0 -62
  226. package/dist/react17/upgrade-to-react-17.js.map +0 -1
  227. package/dist/react18/upgrade-to-react-18.d.ts +0 -12
  228. package/dist/react18/upgrade-to-react-18.d.ts.map +0 -1
  229. package/dist/react18/upgrade-to-react-18.js +0 -64
  230. package/dist/react18/upgrade-to-react-18.js.map +0 -1
  231. package/dist/react19/upgrade-to-react-19.d.ts +0 -8
  232. package/dist/react19/upgrade-to-react-19.d.ts.map +0 -1
  233. package/dist/react19/upgrade-to-react-19.js +0 -68
  234. package/dist/react19/upgrade-to-react-19.js.map +0 -1
  235. package/src/react16/upgrade-to-react-16.ts +0 -59
  236. package/src/react17/upgrade-to-react-17.ts +0 -52
  237. package/src/react18/upgrade-to-react-18.ts +0 -55
  238. package/src/react19/upgrade-to-react-19.ts +0 -75
@@ -0,0 +1,93 @@
1
+ import {check, ExecutionContext, not, TreeVisitor} from "@openrewrite/rewrite";
2
+ import {isVendoredOrBundled, JavaScriptParser, JavaScriptVisitor, JS, namesDeclaredIn} from "@openrewrite/rewrite/javascript";
3
+ import {isIdentifier, J} from "@openrewrite/rewrite/java";
4
+ import {CraProjects, CraScanningRecipe} from "./scan-cra-projects";
5
+ import {craToViteBlockersTable} from "./cra-blockers-table";
6
+ import {baseName, CRA_ENV_PREFIX, nearestRoot, VITE_ENV_PREFIX} from "./shared";
7
+
8
+ /** Node-side files that CRA loads from `src/` and Vite does not process; they cannot use `import.meta`. */
9
+ const NODE_SIDE_FILE = /^(setupProxy|craco\.config|config-overrides|webpack\.config|babel\.config|jest\.config|vite\.config|eslint\.config|postcss\.config|tailwind\.config)\.[cm]?[jt]s$/;
10
+
11
+ /** The variables already recorded per package, kept for the whole run because the editor is created more than once. */
12
+ const recordedNames = new WeakMap<CraProjects, Set<string>>();
13
+
14
+ /** Parsed instead of built by hand so the nodes carry the type attribution and ids a parse gives them. */
15
+ async function importMetaEnv(prefix: J.Space): Promise<J.FieldAccess> {
16
+ const cu = await new JavaScriptParser().parseOne({text: "import.meta.env;", sourcePath: "import-meta-env.ts"}) as JS.CompilationUnit;
17
+ const expression = cu.statements[0].element as unknown as J.FieldAccess;
18
+ return {...expression, prefix};
19
+ }
20
+
21
+ function isProcessEnv(expr: J): expr is J.FieldAccess {
22
+ return expr.kind === J.Kind.FieldAccess &&
23
+ (expr as J.FieldAccess).name.element.simpleName === "env" &&
24
+ isIdentifier((expr as J.FieldAccess).target) &&
25
+ ((expr as J.FieldAccess).target as J.Identifier).simpleName === "process";
26
+ }
27
+
28
+ /**
29
+ * Rewrites `process.env.REACT_APP_NAME` to `import.meta.env.VITE_NAME`.
30
+ *
31
+ * ```ts
32
+ * const url = process.env.REACT_APP_API_URL; -> const url = import.meta.env.VITE_API_URL;
33
+ * ```
34
+ *
35
+ * Only files below the `src/` of a Create React App package change, which is all that CRA bundles; a `server.js`,
36
+ * `scripts/` or `cypress.config.js` beside it may run in Node, where `import.meta` is a syntax error. Only the global `process` is rewritten: a file that declares or imports its own `process` is skipped, as are
37
+ * computed access (`process.env['REACT_APP_X']`), destructuring and Node-side config files, which
38
+ * `FindCraToViteBlockers` reports. `import.meta` is a syntax error under Jest, so code that a Jest test imports
39
+ * needs the tests moved to Vitest.
40
+ *
41
+ * Values that are set outside the `.env` files in the repository (a Dockerfile, CI, a hosting dashboard) still arrive as
42
+ * `REACT_APP_*` and would read as `undefined`, so each renamed variable is recorded once per package in the
43
+ * `CraToViteBlockers` data table with the instruction to define it under its new name.
44
+ *
45
+ * @see https://vite.dev/guide/env-and-mode
46
+ */
47
+ export class RenameProcessEnvReactApp extends CraScanningRecipe {
48
+ readonly name = "org.openrewrite.react.cra-to-vite.rename-process-env-react-app";
49
+ readonly displayName = "Replace `process.env.REACT_APP_*` with `import.meta.env.VITE_*`";
50
+ readonly description = "Rewrites reads of `process.env.REACT_APP_*` to `import.meta.env.VITE_*`, which is how Vite exposes client environment variables. Files that declare their own `process`, computed or destructured access, and Node-side config files, and files outside the package's `src/` folder, are left unchanged. Each renamed variable is recorded in a data table, because values set outside the repository's `.env` files must be renamed too.";
51
+
52
+ async editorWithData(acc: CraProjects): Promise<TreeVisitor<any, ExecutionContext>> {
53
+ const table = craToViteBlockersTable();
54
+ let recorded = recordedNames.get(acc);
55
+ if (!recorded) recordedNames.set(acc, recorded = new Set());
56
+ const seen = recorded;
57
+ return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
58
+ private skipFile = false;
59
+ private path = "";
60
+
61
+ override async visitJsCompilationUnit(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<J | undefined> {
62
+ this.path = cu.sourcePath;
63
+ this.skipFile = NODE_SIDE_FILE.test(baseName(cu.sourcePath)) || !acc.isViteClientSource(cu.sourcePath) || namesDeclaredIn(cu).has("process");
64
+ return this.skipFile ? cu : super.visitJsCompilationUnit(cu, ctx);
65
+ }
66
+
67
+ override async visitFieldAccess(fieldAccess: J.FieldAccess, ctx: ExecutionContext): Promise<J | undefined> {
68
+ const visited = await super.visitFieldAccess(fieldAccess, ctx) as J.FieldAccess;
69
+ const name = visited.name.element.simpleName;
70
+ if (!name.startsWith(CRA_ENV_PREFIX) || name.length === CRA_ENV_PREFIX.length || !isProcessEnv(visited.target)) {
71
+ return visited;
72
+ }
73
+ const renamed = {
74
+ ...visited.name.element,
75
+ simpleName: VITE_ENV_PREFIX + name.substring(CRA_ENV_PREFIX.length)
76
+ };
77
+ const owner = nearestRoot(acc.packageDirs, this.path) ?? "";
78
+ if (!seen.has(`${owner}:${name}`)) {
79
+ seen.add(`${owner}:${name}`);
80
+ table.insertRow(ctx, {
81
+ filePath: this.path, category: "env-definition", detail: `${name} is read as ${renamed.simpleName}`,
82
+ nextStep: `Define ${renamed.simpleName} wherever ${name} is set outside the .env files in this repository (Dockerfile, CI, hosting dashboard), or the value will be undefined at build time.`
83
+ });
84
+ }
85
+ return {
86
+ ...visited,
87
+ target: await importMetaEnv(visited.target.prefix),
88
+ name: {...visited.name, element: renamed},
89
+ } as J.FieldAccess;
90
+ }
91
+ });
92
+ }
93
+ }
@@ -0,0 +1,61 @@
1
+ import {ExecutionContext, TreeVisitor} from "@openrewrite/rewrite";
2
+ import {PlainText, PlainTextVisitor} from "@openrewrite/rewrite/text";
3
+ import {craToViteBlockersTable} from "./cra-blockers-table";
4
+ import {CraProjects, CraScanningRecipe} from "./scan-cra-projects";
5
+ import {CRA_ENV_PREFIX, isEnvFile, VITE_ENV_PREFIX} from "./shared";
6
+
7
+ const ASSIGNMENT = new RegExp(`^(\\s*(?:export\\s+)?)${CRA_ENV_PREFIX}([A-Za-z0-9_]+)(\\s*=)`);
8
+ const EXPANSION = new RegExp(`(\\$\\{?)${CRA_ENV_PREFIX}([A-Za-z0-9_]+)`, "g");
9
+
10
+ /**
11
+ * Renames `REACT_APP_*` variables to `VITE_*` in `.env` files, including `${REACT_APP_*}` expansions.
12
+ *
13
+ * ```
14
+ * REACT_APP_API_URL=https://example.com -> VITE_API_URL=https://example.com
15
+ * ```
16
+ *
17
+ * A variable is left alone and recorded in the blockers data table when the same file already defines the
18
+ * `VITE_` name, so no value is overwritten.
19
+ * Only `.env` files of Create React App packages change. Vite only reads `.env` files in the project root, and they are not moved.
20
+ *
21
+ * @see https://vite.dev/guide/env-and-mode
22
+ */
23
+ export class RenameReactAppEnvVarsInEnvFiles extends CraScanningRecipe {
24
+ readonly name = "org.openrewrite.react.cra-to-vite.rename-env-file-variables";
25
+ readonly displayName = "Rename `REACT_APP_` variables in `.env` files to `VITE_`";
26
+ readonly description = "Renames `REACT_APP_*` variables in `.env` files to the `VITE_*` prefix that Vite exposes to client code, including `${REACT_APP_*}` expansions. Variables whose `VITE_` name is already defined in the same file are left unchanged and recorded in a data table.";
27
+
28
+ async editorWithData(acc: CraProjects): Promise<TreeVisitor<any, ExecutionContext>> {
29
+ const table = craToViteBlockersTable();
30
+ return new class extends PlainTextVisitor<ExecutionContext> {
31
+ protected override async visitText(text: PlainText, ctx: ExecutionContext): Promise<PlainText | undefined> {
32
+ if (!isEnvFile(text.sourcePath) || !acc.isViteFile(text.sourcePath)) return text;
33
+ // Without the prefix there is nothing to rename or to collide with.
34
+ if (!text.text.includes(CRA_ENV_PREFIX)) return text;
35
+ const lines = text.text.split("\n");
36
+ const taken = new Set<string>();
37
+ for (const line of lines) {
38
+ const m = line.match(/^\s*(?:export\s+)?(VITE_[A-Za-z0-9_]+)\s*=/);
39
+ if (m) taken.add(m[1]);
40
+ }
41
+ const reported = new Set<string>();
42
+ const renamable = (name: string) => {
43
+ if (!taken.has(VITE_ENV_PREFIX + name)) return true;
44
+ if (!reported.has(name)) table.insertRow(ctx, {
45
+ filePath: text.sourcePath, category: "env-collision", detail: `${CRA_ENV_PREFIX}${name} was not renamed`,
46
+ nextStep: `${VITE_ENV_PREFIX}${name} is already defined in this file; merge the two by hand.`
47
+ });
48
+ reported.add(name);
49
+ return false;
50
+ };
51
+ const updated = lines.map(line =>
52
+ line.replace(ASSIGNMENT, (whole, lead, name, eq) =>
53
+ renamable(name) ? `${lead}${VITE_ENV_PREFIX}${name}${eq}` : whole)
54
+ .replace(EXPANSION, (whole, lead, name) =>
55
+ renamable(name) ? `${lead}${VITE_ENV_PREFIX}${name}` : whole)
56
+ ).join("\n");
57
+ return updated === text.text ? text : {...text, text: updated};
58
+ }
59
+ };
60
+ }
61
+ }
@@ -0,0 +1,71 @@
1
+ import {ExecutionContext, Option, Recipe, TreeVisitor} from "@openrewrite/rewrite";
2
+ import {Json, jsonLiteral, JsonVisitor, removeAt, setAt} from "@openrewrite/rewrite/json";
3
+ import {
4
+ hasDependency, memberObject, newMemberPosition, runsOnVite, isPackageJson, rootObject, scriptsKeepReactScripts, REACT_SCRIPTS, VITE, VITE_PLUGIN_REACT
5
+ } from "./shared";
6
+
7
+ /**
8
+ * Adds `vite` and `@vitejs/plugin-react` to `devDependencies` of a package that depends on `react-scripts`,
9
+ * and removes `react-scripts` once no script invokes it any more.
10
+ *
11
+ * ```json
12
+ * "dependencies": {"react-scripts": "5.0.1"} -> "devDependencies": {"@vitejs/plugin-react": "^5.2.0", "vite": "^7.0.0"}
13
+ * ```
14
+ *
15
+ * The default versions are a peer-consistent pair that both need Node 20.19 or later. `react-scripts` stays
16
+ * while a script such as `test` still runs it, because it provides Jest. The `eject` script does not count, and
17
+ * `UpdateReactScriptsScripts` removes it. A package that `craco`, `react-app-rewired` or a wrapped `start` or
18
+ * `build` script still depends on `react-scripts` is left to the finders.
19
+ *
20
+ * @see https://react.dev/blog/2025/02/14/sunsetting-create-react-app#how-to-migrate-to-a-build-tool
21
+ */
22
+ export class ReplaceReactScriptsDependency extends Recipe {
23
+ readonly name = "org.openrewrite.react.cra-to-vite.replace-react-scripts-dependency";
24
+ readonly displayName = "Replace `react-scripts` dependency with Vite";
25
+ readonly description = "Adds `vite` and `@vitejs/plugin-react` as dev dependencies of projects that depend on `react-scripts`, and removes `react-scripts` unless a script other than `eject` still invokes it (for example `react-scripts test`, which the stock Create React App template keeps, so the dependency usually stays until the tests move to Vitest). Packages that use `craco`, `react-app-rewired` or wrapped `start` or `build` scripts are left unchanged. The lock file is not regenerated; run your package manager afterwards.";
26
+
27
+ @Option({
28
+ displayName: "Vite version",
29
+ description: "The version range of `vite` to add. Vite 7 needs Node 20.19 or later.",
30
+ example: "^7.0.0",
31
+ required: false
32
+ })
33
+ viteVersion?: string;
34
+
35
+ @Option({
36
+ displayName: "Vite React plugin version",
37
+ description: "The version range of `@vitejs/plugin-react` to add. It must accept the `vite` range above.",
38
+ example: "^5.2.0",
39
+ required: false
40
+ })
41
+ pluginReactVersion?: string;
42
+
43
+ constructor(options?: { viteVersion?: string; pluginReactVersion?: string }) {
44
+ super(options);
45
+ this.viteVersion ??= "^7.0.0";
46
+ this.pluginReactVersion ??= "^5.2.0";
47
+ }
48
+
49
+ async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
50
+ const viteVersion = this.viteVersion!;
51
+ const pluginVersion = this.pluginReactVersion!;
52
+ return new class extends JsonVisitor<ExecutionContext> {
53
+ protected override async visitDocument(doc: Json.Document): Promise<Json | undefined> {
54
+ const pkg = rootObject(doc);
55
+ if (!pkg || !isPackageJson(doc.sourcePath) || !runsOnVite(pkg)) return doc;
56
+
57
+ const position = newMemberPosition(memberObject(pkg, "devDependencies"));
58
+ const parentPosition = newMemberPosition(pkg);
59
+ let updated = doc;
60
+ for (const [name, version] of [[VITE, viteVersion], [VITE_PLUGIN_REACT, pluginVersion]]) {
61
+ if (hasDependency(pkg, name)) continue;
62
+ updated = setAt(updated, ["devDependencies", name], jsonLiteral(version), {createMissing: true, position, parentPosition});
63
+ }
64
+ if (!scriptsKeepReactScripts(pkg)) {
65
+ for (const section of ["dependencies", "devDependencies"]) updated = removeAt(updated, [section, REACT_SCRIPTS]);
66
+ }
67
+ return updated;
68
+ }
69
+ };
70
+ }
71
+ }
@@ -0,0 +1,86 @@
1
+ import {ExecutionContext, ScanningRecipe, Tree, TreeVisitor} from "@openrewrite/rewrite";
2
+ import {Json} from "@openrewrite/rewrite/json";
3
+ import {PlainText} from "@openrewrite/rewrite/text";
4
+ import {baseName, dirName, isCraPackage, runsOnVite, nearestRoot, isPackageJson, joinPath, rootObject} from "./shared";
5
+
6
+ /** What the recipes that add or move files need to know about the whole repository before they edit it. */
7
+ export class CraProjects {
8
+ /** Directories of the `package.json` files that Create React App built; `''` is the repository root. */
9
+ readonly roots = new Set<string>();
10
+ /** The subset of `roots` whose `start` and `build` will run on Vite, the only ones the edit recipes change. */
11
+ readonly viteRoots = new Set<string>();
12
+ /** Directories of every `package.json`, CRA or not, to tell which package a file belongs to. */
13
+ readonly packageDirs = new Set<string>();
14
+ /** Every source path in the repository, to tell whether a file already exists. */
15
+ readonly paths = new Set<string>();
16
+ /** The `public/index.html` text of each directory. */
17
+ readonly indexHtml = new Map<string, string>();
18
+
19
+ /**
20
+ * True when the file belongs to a Create React App package: the nearest `package.json` above it, not any
21
+ * package higher up, depends on `react-scripts`. A Node server in `server/` of a CRA repository does not.
22
+ */
23
+ isCraFile(sourcePath: string): boolean {
24
+ const owner = nearestRoot(this.packageDirs, sourcePath);
25
+ return owner !== undefined && this.roots.has(owner);
26
+ }
27
+
28
+ /** True when the file belongs to a package whose `start` and `build` will run on Vite, so the edit recipes may change it. */
29
+ isViteFile(sourcePath: string): boolean {
30
+ const owner = nearestRoot(this.packageDirs, sourcePath);
31
+ return owner !== undefined && this.viteRoots.has(owner);
32
+ }
33
+
34
+ /** True when the file is client code that CRA bundled: below the `src/` of a package that runs on Vite. */
35
+ isViteClientSource(sourcePath: string): boolean {
36
+ const owner = nearestRoot(this.packageDirs, sourcePath);
37
+ return owner !== undefined && this.viteRoots.has(owner) && sourcePath.startsWith(joinPath(owner, "src/"));
38
+ }
39
+
40
+ has(root: string, name: string): boolean {
41
+ return this.paths.has(joinPath(root, name));
42
+ }
43
+
44
+ /** The first of `names` that exists below `root`. */
45
+ firstExisting(root: string, names: string[]): string | undefined {
46
+ return names.find(name => this.has(root, name));
47
+ }
48
+ }
49
+
50
+ /** The package root a `public/index.html` belongs to, or `undefined` when the path is not one. */
51
+ export function indexHtmlRoot(sourcePath: string): string | undefined {
52
+ return baseName(sourcePath) === "index.html" && baseName(dirName(sourcePath)) === "public" ?
53
+ dirName(dirName(sourcePath)) : undefined;
54
+ }
55
+
56
+ export const VITE_CONFIG_NAMES = ["vite.config.ts", "vite.config.js", "vite.config.mts", "vite.config.mjs", "vite.config.cts", "vite.config.cjs"];
57
+
58
+ export function scanCraProjects(acc: CraProjects): TreeVisitor<any, ExecutionContext> {
59
+ return new class extends TreeVisitor<Tree, ExecutionContext> {
60
+ override async visit<R extends Tree>(tree: Tree): Promise<R | undefined> {
61
+ const sourcePath = (tree as { sourcePath?: string }).sourcePath;
62
+ if (sourcePath === undefined) return tree as R;
63
+ acc.paths.add(sourcePath);
64
+ if (tree.kind === Json.Kind.Document && isPackageJson(sourcePath)) {
65
+ acc.packageDirs.add(dirName(sourcePath));
66
+ const pkg = rootObject(tree as Json.Document);
67
+ if (pkg && isCraPackage(pkg)) acc.roots.add(dirName(sourcePath));
68
+ if (pkg && runsOnVite(pkg)) acc.viteRoots.add(dirName(sourcePath));
69
+ } else if (tree.kind === PlainText.Kind.PlainText && indexHtmlRoot(sourcePath) !== undefined) {
70
+ acc.indexHtml.set(indexHtmlRoot(sourcePath)!, (tree as PlainText).text);
71
+ }
72
+ return tree as R;
73
+ }
74
+ };
75
+ }
76
+
77
+ /** A recipe that scans the whole repository for Create React App packages. Finders use `isCraFile`, edits `isViteFile`. */
78
+ export abstract class CraScanningRecipe extends ScanningRecipe<CraProjects> {
79
+ initialValue(): CraProjects {
80
+ return new CraProjects();
81
+ }
82
+
83
+ async scanner(acc: CraProjects): Promise<TreeVisitor<any, ExecutionContext>> {
84
+ return scanCraProjects(acc);
85
+ }
86
+ }
@@ -0,0 +1,123 @@
1
+ import {elementsOf, findMember, getMemberKeyName, isLiteral, isObject, Json, membersOf, valueAt} from "@openrewrite/rewrite/json";
2
+
3
+ export const REACT_SCRIPTS = "react-scripts";
4
+ export const VITE = "vite";
5
+ export const VITE_PLUGIN_REACT = "@vitejs/plugin-react";
6
+
7
+ /** `REACT_APP_NAME`, the prefix Create React App exposes to client code. */
8
+ export const CRA_ENV_PREFIX = "REACT_APP_";
9
+ export const VITE_ENV_PREFIX = "VITE_";
10
+
11
+ const DEPENDENCY_SECTIONS = ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"];
12
+
13
+ /** The directory of a path with no trailing slash; `''` for a root-level file. */
14
+ export function dirName(path: string): string {
15
+ const i = path.lastIndexOf("/");
16
+ return i < 0 ? "" : path.substring(0, i);
17
+ }
18
+
19
+ export function baseName(path: string): string {
20
+ return path.substring(path.lastIndexOf("/") + 1);
21
+ }
22
+
23
+ export function joinPath(dir: string, name: string): string {
24
+ return dir === "" ? name : `${dir}/${name}`;
25
+ }
26
+
27
+ /** The nearest of `roots` that is a directory above `path`, found by climbing its ancestors. */
28
+ export function nearestRoot(roots: ReadonlySet<string>, path: string): string | undefined {
29
+ for (let dir = dirName(path); ; dir = dirName(dir)) {
30
+ if (roots.has(dir)) return dir;
31
+ if (dir === "") return undefined;
32
+ }
33
+ }
34
+
35
+ export function isPackageJson(sourcePath: string): boolean {
36
+ return baseName(sourcePath) === "package.json" && !sourcePath.split("/").includes("node_modules");
37
+ }
38
+
39
+ export function rootObject(doc: Json.Document): Json.Object | undefined {
40
+ return isObject(doc.value) ? doc.value : undefined;
41
+ }
42
+
43
+ export function memberObject(obj: Json.Object, name: string): Json.Object | undefined {
44
+ const value = findMember(obj, name)?.value;
45
+ return value && isObject(value) ? value : undefined;
46
+ }
47
+
48
+ /** The string a JSON value holds, or `undefined` when it is not a string literal. */
49
+ export function stringValue(value: Json | undefined): string | undefined {
50
+ return value && isLiteral(value) && typeof value.value === "string" ? value.value : undefined;
51
+ }
52
+
53
+ export function hasDependency(pkg: Json.Object, name: string): boolean {
54
+ return DEPENDENCY_SECTIONS.some(section => valueAt(pkg, [section, name]) !== undefined);
55
+ }
56
+
57
+ /** True when a package.json script invokes `react-scripts`. */
58
+ export function scriptsUseReactScripts(pkg: Json.Object): boolean {
59
+ const scripts = memberObject(pkg, "scripts");
60
+ return !!scripts && membersOf(scripts).some(m => {
61
+ const command = stringValue(m.value);
62
+ return command !== undefined && /(^|[\s&;|])react-scripts(\s|$)/.test(command);
63
+ });
64
+ }
65
+
66
+ /** A `package.json` that Create React App built: `react-scripts` is a dependency. */
67
+ export function isCraPackage(pkg: Json.Object): boolean {
68
+ return hasDependency(pkg, REACT_SCRIPTS);
69
+ }
70
+
71
+ /** Tools that wrap or replace `react-scripts`, and which Vite does not replace. */
72
+ const WRAPPER_DEPENDENCIES = ["@craco/craco", "craco", "react-app-rewired"];
73
+ const WRAPPER_COMMAND = /(^|[\s&;|])(craco|react-app-rewired)(\s|$)/;
74
+ const START_OR_BUILD = /(^|[\s&;|])react-scripts\s+(start|build)(\s|$)/;
75
+ /** The only commands the migration rewrites. */
76
+ export const EXACT_START_OR_BUILD = /^react-scripts (start|build)$/;
77
+
78
+ /**
79
+ * True when the package's `start` and `build` will run on Vite once the migration has edited it: it is a Create
80
+ * React App package that neither depends on `craco` or `react-app-rewired` nor has a script that wraps those or
81
+ * `react-scripts start|build` (`cross-env PORT=4000 react-scripts start`, `react-scripts build --profile`).
82
+ * Such a package is only found by the finders; editing it would leave `start` or `build` without a working tool.
83
+ */
84
+ export function runsOnVite(pkg: Json.Object): boolean {
85
+ if (!isCraPackage(pkg) || WRAPPER_DEPENDENCIES.some(name => hasDependency(pkg, name))) return false;
86
+ const scripts = memberObject(pkg, "scripts");
87
+ return !scripts || membersOf(scripts).every(m => {
88
+ const command = stringValue(m.value)?.trim();
89
+ return command === undefined || (!WRAPPER_COMMAND.test(command) &&
90
+ (!START_OR_BUILD.test(command) || EXACT_START_OR_BUILD.test(command)));
91
+ });
92
+ }
93
+
94
+ /**
95
+ * True when a script still needs `react-scripts` once the migration is done, that is any script that runs it
96
+ * other than `eject`, which the migration removes.
97
+ */
98
+ export function scriptsKeepReactScripts(pkg: Json.Object): boolean {
99
+ const scripts = memberObject(pkg, "scripts");
100
+ return !!scripts && membersOf(scripts).some(m => {
101
+ const command = stringValue(m.value);
102
+ return command !== undefined && /(^|[\s&;|])react-scripts(\s|$)/.test(command) &&
103
+ !/(^|[\s&;|])react-scripts\s+eject\s*$/.test(command);
104
+ });
105
+ }
106
+
107
+ /**
108
+ * Where a new member goes: in key order when the object's keys are already sorted, the way npm keeps its dependency
109
+ * sections, and last otherwise, so a hand-ordered `package.json` keeps its order.
110
+ */
111
+ export function newMemberPosition(obj: Json.Object | undefined): "sorted" | "last" {
112
+ const keys = obj ? membersOf(obj).map(m => getMemberKeyName(m) ?? "") : [];
113
+ return keys.every((key, i) => i === 0 || keys[i - 1].localeCompare(key, "en") <= 0) ? "sorted" : "last";
114
+ }
115
+
116
+ /** `.env`, `.env.local`, `.env.production.local` and the like. */
117
+ export function isEnvFile(sourcePath: string): boolean {
118
+ return /^\.env(\..+)?$/.test(baseName(sourcePath));
119
+ }
120
+
121
+ export function stringValues(array: Json.Array): string[] {
122
+ return elementsOf(array).flatMap(value => stringValue(value) ?? []);
123
+ }
@@ -0,0 +1,40 @@
1
+ import {ExecutionContext, TreeVisitor} from "@openrewrite/rewrite";
2
+ import {JavaScriptVisitor, JS} from "@openrewrite/rewrite/javascript";
3
+ import {J} from "@openrewrite/rewrite/java";
4
+ import {CraProjects, CraScanningRecipe} from "./scan-cra-projects";
5
+ import {baseName} from "./shared";
6
+
7
+ /** The `///` of a triple-slash directive is parsed as the comment's `//`, leaving `/ <reference ... />` as its text. */
8
+ const REACT_SCRIPTS_REFERENCE = /^\/ <reference types="react-scripts" \/>$/;
9
+ const VITE_CLIENT_REFERENCE = '/ <reference types="vite/client" />';
10
+
11
+ /**
12
+ * Points the triple-slash type reference that Create React App generates at Vite's client types.
13
+ *
14
+ * ```ts
15
+ * /// <reference types="react-scripts" /> -> /// <reference types="vite/client" />
16
+ * ```
17
+ *
18
+ * The `react-scripts` package types no longer resolve once `react-scripts` is removed. `vite/client` declares
19
+ * `import.meta.env`, asset imports and CSS modules.
20
+ *
21
+ * @see https://vite.dev/guide/features#client-types
22
+ */
23
+ export class UpdateReactAppEnvTypes extends CraScanningRecipe {
24
+ readonly name = "org.openrewrite.react.cra-to-vite.update-react-app-env-types";
25
+ readonly displayName = "Reference `vite/client` instead of `react-scripts` types";
26
+ readonly description = "Replaces `/// <reference types=\"react-scripts\" />` in declaration files of Create React App packages, such as `src/react-app-env.d.ts`, with `/// <reference types=\"vite/client\" />`.";
27
+
28
+ async editorWithData(acc: CraProjects): Promise<TreeVisitor<any, ExecutionContext>> {
29
+ return new class extends JavaScriptVisitor<ExecutionContext> {
30
+ override async visitJsCompilationUnit(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<J | undefined> {
31
+ if (!baseName(cu.sourcePath).endsWith(".d.ts") || !acc.isViteFile(cu.sourcePath)) return cu;
32
+ const comments = cu.prefix.comments.map(c =>
33
+ c.kind === J.Kind.TextComment && REACT_SCRIPTS_REFERENCE.test((c as unknown as {text: string}).text) ?
34
+ {...c, text: VITE_CLIENT_REFERENCE} : c);
35
+ if (comments.every((c, i) => c === cu.prefix.comments[i])) return super.visitJsCompilationUnit(cu, ctx);
36
+ return {...cu, prefix: {...cu.prefix, comments}} as JS.CompilationUnit;
37
+ }
38
+ };
39
+ }
40
+ }
@@ -0,0 +1,64 @@
1
+ import {ExecutionContext, TreeVisitor} from "@openrewrite/rewrite";
2
+ import {getMemberKeyName, isObject, Json, jsonLiteral, JsonVisitor, membersOf, removeAt, setAt} from "@openrewrite/rewrite/json";
3
+ import {CraProjects, CraScanningRecipe} from "./scan-cra-projects";
4
+ import {dirName, isPackageJson, memberObject, runsOnVite, stringValue} from "./shared";
5
+
6
+ /** Only an exact match is rewritten: extra flags or environment prefixes need a human. */
7
+ const SCRIPT_REPLACEMENTS = new Map<string, string>([
8
+ ["react-scripts start", "vite"],
9
+ ["react-scripts build", "vite build"],
10
+ ]);
11
+
12
+ /** `react-scripts build` fails the build on type errors; `vite build` does not type-check, so a project with a tsconfig keeps the check. */
13
+ const TYPE_CHECKED_BUILD = "tsc --noEmit && vite build";
14
+
15
+ /**
16
+ * Rewrites scripts whose command is exactly `react-scripts start` and `react-scripts build`.
17
+ *
18
+ * ```json
19
+ * "start": "react-scripts start" -> "start": "vite"
20
+ * "build": "react-scripts build" -> "build": "vite build"
21
+ * "build": "react-scripts build" -> "build": "tsc --noEmit && vite build" (when there is a tsconfig.json)
22
+ * "eject": "react-scripts eject" -> (removed)
23
+ * ```
24
+ *
25
+ * `react-scripts build` failed on type errors and `vite build` does not type-check, so a package with a `tsconfig.json`
26
+ * keeps the check. `--noEmit` rather than `tsc -b`, because the CRA tsconfig sets `noEmit` and `tsc -b` rejects that before TypeScript 5.6.
27
+ *
28
+ * Only packages that depend on `react-scripts` change; in a workspace that hoists it the scripts are left alone. A package
29
+ * with a script that wraps `react-scripts start|build` or runs `craco` is not edited at all, because a half-migrated
30
+ * package has no working `start`. Scripts with extra flags (`cross-env PORT=4000 react-scripts start`) and `test` are left for
31
+ * `FindCraToViteBlockers` to flag.
32
+ *
33
+ * @see https://react.dev/blog/2025/02/14/sunsetting-create-react-app#how-to-migrate-to-a-build-tool
34
+ */
35
+ export class UpdateReactScriptsScripts extends CraScanningRecipe {
36
+ readonly name = "org.openrewrite.react.cra-to-vite.update-package-scripts";
37
+ readonly displayName = "Replace `react-scripts` start and build scripts with Vite";
38
+ readonly description = "Rewrites `package.json` scripts that are exactly `react-scripts start` or `react-scripts build` to `vite` and `vite build` (`tsc --noEmit && vite build` when there is a `tsconfig.json`), and removes the `react-scripts eject` script, in packages that depend on `react-scripts`. Packages with `craco`, `react-app-rewired` or wrapped `start` or `build` scripts are left unchanged, as is the `test` script.";
39
+
40
+ async editorWithData(acc: CraProjects): Promise<TreeVisitor<any, ExecutionContext>> {
41
+ return new class extends JsonVisitor<ExecutionContext> {
42
+ protected override async visitDocument(doc: Json.Document): Promise<Json | undefined> {
43
+ if (!isPackageJson(doc.sourcePath) || !isObject(doc.value) || !runsOnVite(doc.value)) return doc;
44
+ const scripts = memberObject(doc.value, "scripts");
45
+ if (!scripts) return doc;
46
+ const build = acc.has(dirName(doc.sourcePath), "tsconfig.json") ? TYPE_CHECKED_BUILD : "vite build";
47
+ let updated = doc;
48
+ for (const m of membersOf(scripts)) {
49
+ const name = getMemberKeyName(m);
50
+ const command = stringValue(m.value)?.trim();
51
+ if (name === undefined || command === undefined) continue;
52
+ // `eject` has no Vite equivalent and is the last thing that keeps react-scripts installed.
53
+ if (command === "react-scripts eject") {
54
+ updated = removeAt(updated, ["scripts", name]);
55
+ continue;
56
+ }
57
+ const replacement = SCRIPT_REPLACEMENTS.get(command);
58
+ if (replacement) updated = setAt(updated, ["scripts", name], jsonLiteral(replacement === "vite build" ? build : replacement));
59
+ }
60
+ return updated;
61
+ }
62
+ };
63
+ }
64
+ }
@@ -0,0 +1,40 @@
1
+ import {ExecutionContext, TreeVisitor} from "@openrewrite/rewrite";
2
+ import {appendElement, elementsOf, isArray, Json, jsonLiteral, JsonVisitor, updateAt} from "@openrewrite/rewrite/json";
3
+ import {CraProjects, CraScanningRecipe} from "./scan-cra-projects";
4
+ import {baseName} from "./shared";
5
+
6
+ const TYPES_PATH = ["compilerOptions", "types"];
7
+
8
+ export function isTsConfig(sourcePath: string): boolean {
9
+ return /^tsconfig(\..+)?\.json$/.test(baseName(sourcePath)) && !sourcePath.split("/").includes("node_modules");
10
+ }
11
+
12
+ /**
13
+ * Adds `vite/client` to an existing `compilerOptions.types` list in `tsconfig.json`, so `import.meta.env` and
14
+ * asset imports type-check.
15
+ *
16
+ * ```json
17
+ * "types": ["node"] -> "types": ["node", "vite/client"]
18
+ * ```
19
+ *
20
+ * Only tsconfig files of Create React App packages change. A tsconfig without a `types` list is left alone, because adding one would stop TypeScript from including
21
+ * every `@types/*` package automatically; `UpdateReactAppEnvTypes` points `src/react-app-env.d.ts` at
22
+ * `vite/client` for those projects.
23
+ *
24
+ * @see https://vite.dev/guide/features#client-types
25
+ */
26
+ export class UpdateTsconfigForVite extends CraScanningRecipe {
27
+ readonly name = "org.openrewrite.react.cra-to-vite.update-tsconfig";
28
+ readonly displayName = "Add `vite/client` types to `tsconfig.json`";
29
+ readonly description = "Appends `vite/client` to an existing `compilerOptions.types` list in `tsconfig.json` files. Files without a `types` list are left unchanged so that TypeScript keeps including every `@types/*` package.";
30
+
31
+ async editorWithData(acc: CraProjects): Promise<TreeVisitor<any, ExecutionContext>> {
32
+ return new class extends JsonVisitor<ExecutionContext> {
33
+ protected override async visitDocument(doc: Json.Document): Promise<Json | undefined> {
34
+ if (!isTsConfig(doc.sourcePath) || !acc.isViteFile(doc.sourcePath)) return doc;
35
+ return updateAt(doc, TYPES_PATH, types => isArray(types) && elementsOf(types).length > 0 ?
36
+ appendElement(types, jsonLiteral("vite/client"), {unique: true}) : types);
37
+ }
38
+ };
39
+ }
40
+ }