@openrewrite/recipes-react 0.14.0 → 0.15.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 (204) 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 +185 -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 +98 -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 +37 -0
  58. package/dist/migration/cra-to-vite/shared.d.ts.map +1 -0
  59. package/dist/migration/cra-to-vite/shared.js +218 -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 +67 -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 +53 -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 +169 -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/refactoring/class-to-functional.d.ts.map +1 -1
  89. package/dist/refactoring/class-to-functional.js +81 -7
  90. package/dist/refactoring/class-to-functional.js.map +1 -1
  91. package/dist/refactoring/fix-async-effect.d.ts +8 -0
  92. package/dist/refactoring/fix-async-effect.d.ts.map +1 -0
  93. package/dist/refactoring/fix-async-effect.js +71 -0
  94. package/dist/refactoring/fix-async-effect.js.map +1 -0
  95. package/dist/refactoring/prop-types-to-typescript.d.ts +8 -0
  96. package/dist/refactoring/prop-types-to-typescript.d.ts.map +1 -0
  97. package/dist/refactoring/prop-types-to-typescript.js +342 -0
  98. package/dist/refactoring/prop-types-to-typescript.js.map +1 -0
  99. package/dist/search/find-deprecated-lifecycles.d.ts +12 -0
  100. package/dist/search/find-deprecated-lifecycles.d.ts.map +1 -0
  101. package/dist/search/find-deprecated-lifecycles.js +86 -0
  102. package/dist/search/find-deprecated-lifecycles.js.map +1 -0
  103. package/dist/search/find-effects-without-cleanup.d.ts +9 -0
  104. package/dist/search/find-effects-without-cleanup.d.ts.map +1 -0
  105. package/dist/search/find-effects-without-cleanup.js +133 -0
  106. package/dist/search/find-effects-without-cleanup.js.map +1 -0
  107. package/dist/search/find-enzyme-usage.d.ts +9 -0
  108. package/dist/search/find-enzyme-usage.d.ts.map +1 -0
  109. package/dist/search/find-enzyme-usage.js +155 -0
  110. package/dist/search/find-enzyme-usage.js.map +1 -0
  111. package/dist/search/find-function-component-default-props.d.ts +11 -0
  112. package/dist/search/find-function-component-default-props.d.ts.map +1 -0
  113. package/dist/search/find-function-component-default-props.js +96 -0
  114. package/dist/search/find-function-component-default-props.js.map +1 -0
  115. package/dist/search/find-legacy-react-apis.d.ts +8 -0
  116. package/dist/search/find-legacy-react-apis.d.ts.map +1 -0
  117. package/dist/search/find-legacy-react-apis.js +41 -0
  118. package/dist/search/find-legacy-react-apis.js.map +1 -0
  119. package/dist/search/find-missing-use-client-directive.d.ts +9 -0
  120. package/dist/search/find-missing-use-client-directive.d.ts.map +1 -0
  121. package/dist/search/find-missing-use-client-directive.js +127 -0
  122. package/dist/search/find-missing-use-client-directive.js.map +1 -0
  123. package/dist/search/find-reactdom-root-apis.d.ts +14 -0
  124. package/dist/search/find-reactdom-root-apis.d.ts.map +1 -0
  125. package/dist/search/find-reactdom-root-apis.js +122 -0
  126. package/dist/search/find-reactdom-root-apis.js.map +1 -0
  127. package/dist/testing/enzyme-to-react-testing-library.d.ts +36 -0
  128. package/dist/testing/enzyme-to-react-testing-library.d.ts.map +1 -0
  129. package/dist/testing/enzyme-to-react-testing-library.js +547 -0
  130. package/dist/testing/enzyme-to-react-testing-library.js.map +1 -0
  131. package/dist/testing/enzyme-usage.d.ts +22 -0
  132. package/dist/testing/enzyme-usage.d.ts.map +1 -0
  133. package/dist/testing/enzyme-usage.js +107 -0
  134. package/dist/testing/enzyme-usage.js.map +1 -0
  135. package/dist/testing/enzyme-wrapper-scope.d.ts +42 -0
  136. package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -0
  137. package/dist/testing/enzyme-wrapper-scope.js +422 -0
  138. package/dist/testing/enzyme-wrapper-scope.js.map +1 -0
  139. package/dist/util/react-class.d.ts +6 -0
  140. package/dist/util/react-class.d.ts.map +1 -0
  141. package/dist/util/react-class.js +41 -0
  142. package/dist/util/react-class.js.map +1 -0
  143. package/dist/util/tree-search.d.ts +6 -0
  144. package/dist/util/tree-search.d.ts.map +1 -0
  145. package/dist/util/tree-search.js +51 -0
  146. package/dist/util/tree-search.js.map +1 -0
  147. package/package.json +7 -4
  148. package/src/index.ts +53 -12
  149. package/src/migration/cra-to-vite/add-vite-config.ts +47 -0
  150. package/src/migration/cra-to-vite/cra-blockers-table.ts +27 -0
  151. package/src/migration/cra-to-vite/cra-to-vite.ts +76 -0
  152. package/src/migration/cra-to-vite/find-cra-config-blockers.ts +179 -0
  153. package/src/migration/cra-to-vite/find-cra-env-file-blockers.ts +60 -0
  154. package/src/migration/cra-to-vite/find-cra-source-blockers.ts +138 -0
  155. package/src/migration/cra-to-vite/find-cra-to-vite-blockers.ts +21 -0
  156. package/src/migration/cra-to-vite/index.ts +26 -0
  157. package/src/migration/cra-to-vite/move-public-index-html.ts +132 -0
  158. package/src/migration/cra-to-vite/rename-process-env-react-app.ts +93 -0
  159. package/src/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.ts +61 -0
  160. package/src/migration/cra-to-vite/replace-react-scripts-dependency.ts +96 -0
  161. package/src/migration/cra-to-vite/scan-cra-projects.ts +86 -0
  162. package/src/migration/cra-to-vite/shared.ts +244 -0
  163. package/src/migration/cra-to-vite/update-react-app-env-types.ts +40 -0
  164. package/src/migration/cra-to-vite/update-react-scripts-scripts.ts +69 -0
  165. package/src/migration/cra-to-vite/update-tsconfig-for-vite.ts +47 -0
  166. package/src/react17/migrate-deprecated-lifecycles.ts +265 -0
  167. package/src/react17/use-new-jsx-transform.ts +150 -0
  168. package/src/react18/add-children-to-props.ts +235 -0
  169. package/src/react18/replace-reactdom-render.ts +109 -20
  170. package/src/refactoring/class-to-functional.ts +101 -13
  171. package/src/refactoring/fix-async-effect.ts +88 -0
  172. package/src/refactoring/prop-types-to-typescript.ts +341 -0
  173. package/src/search/find-deprecated-lifecycles.ts +64 -0
  174. package/src/search/find-effects-without-cleanup.ts +109 -0
  175. package/src/search/find-enzyme-usage.ts +117 -0
  176. package/src/search/find-function-component-default-props.ts +68 -0
  177. package/src/search/find-legacy-react-apis.ts +41 -0
  178. package/src/search/find-missing-use-client-directive.ts +99 -0
  179. package/src/search/find-reactdom-root-apis.ts +99 -0
  180. package/src/testing/enzyme-to-react-testing-library.ts +553 -0
  181. package/src/testing/enzyme-usage.ts +94 -0
  182. package/src/testing/enzyme-wrapper-scope.ts +449 -0
  183. package/src/util/react-class.ts +34 -0
  184. package/src/util/tree-search.ts +32 -0
  185. package/dist/react16/upgrade-to-react-16.d.ts +0 -12
  186. package/dist/react16/upgrade-to-react-16.d.ts.map +0 -1
  187. package/dist/react16/upgrade-to-react-16.js +0 -66
  188. package/dist/react16/upgrade-to-react-16.js.map +0 -1
  189. package/dist/react17/upgrade-to-react-17.d.ts +0 -12
  190. package/dist/react17/upgrade-to-react-17.d.ts.map +0 -1
  191. package/dist/react17/upgrade-to-react-17.js +0 -62
  192. package/dist/react17/upgrade-to-react-17.js.map +0 -1
  193. package/dist/react18/upgrade-to-react-18.d.ts +0 -12
  194. package/dist/react18/upgrade-to-react-18.d.ts.map +0 -1
  195. package/dist/react18/upgrade-to-react-18.js +0 -64
  196. package/dist/react18/upgrade-to-react-18.js.map +0 -1
  197. package/dist/react19/upgrade-to-react-19.d.ts +0 -8
  198. package/dist/react19/upgrade-to-react-19.d.ts.map +0 -1
  199. package/dist/react19/upgrade-to-react-19.js +0 -68
  200. package/dist/react19/upgrade-to-react-19.js.map +0 -1
  201. package/src/react16/upgrade-to-react-16.ts +0 -59
  202. package/src/react17/upgrade-to-react-17.ts +0 -52
  203. package/src/react18/upgrade-to-react-18.ts +0 -55
  204. package/src/react19/upgrade-to-react-19.ts +0 -75
@@ -0,0 +1,179 @@
1
+ import {ExecutionContext, foundSearchResult, MarkersKind, Option, SearchResult, TreeVisitor} from "@openrewrite/rewrite";
2
+ import {getMemberKeyName, isMember, Json, JsonVisitor} from "@openrewrite/rewrite/json";
3
+ import {CraProjects, CraScanningRecipe} from "./scan-cra-projects";
4
+ import {craToViteBlockersTable} from "./cra-blockers-table";
5
+ import {
6
+ getMember, hasDependency, isCraPackage, isPackageJson, memberObject, rootObject, scriptsUseReactScripts,
7
+ stringMember, stringValue, stringValues
8
+ } from "./shared";
9
+ import {isTsConfig} from "./update-tsconfig-for-vite";
10
+
11
+ const CONFIG_TOOLS = ["@craco/craco", "craco", "react-app-rewired", "customize-cra"];
12
+ const TOOL_SCRIPT = /(^|[\s&;|])(craco|react-app-rewired)(\s|$)/;
13
+ const REACT_SCRIPTS_COMMAND = /(^|[\s&;|])react-scripts\s+(\w+)/;
14
+
15
+ interface Finding {
16
+ category: string;
17
+ detail: string;
18
+ nextStep: string;
19
+ }
20
+
21
+ /**
22
+ * Finds `package.json` and `tsconfig.json` settings that a Create React App to Vite migration does not rewrite:
23
+ * `craco` and `react-app-rewired`, `react-scripts test` and `eject` scripts, the `jest` and `eslintConfig` blocks,
24
+ * `proxy`, `homepage` and a `baseUrl` for absolute imports.
25
+ *
26
+ * Each finding is a row in the blockers data table and, unless `markResults` is off, a search result on the
27
+ * entry. A search result is a comment, which JSON cannot hold, so the migration that applies changes runs
28
+ * this recipe with `markResults` off.
29
+ *
30
+ * @see https://react.dev/blog/2025/02/14/sunsetting-create-react-app#how-to-migrate-to-a-build-tool
31
+ */
32
+ export class FindCraConfigBlockers extends CraScanningRecipe {
33
+ readonly name = "org.openrewrite.react.cra-to-vite.find-config-blockers";
34
+ readonly displayName = "Find Create React App configuration that needs a manual Vite migration";
35
+ readonly description = "Finds `craco` and `react-app-rewired` setups, `react-scripts` scripts that remain, `jest`, `eslintConfig`, `proxy` and `homepage` settings in `package.json`, and a `baseUrl` in `tsconfig.json`, and records each in a data table.";
36
+
37
+ private dataTable = craToViteBlockersTable();
38
+
39
+ @Option({
40
+ displayName: "Mark results",
41
+ description: "Whether to put a search result on each finding. Search results print as comments, which are not valid in JSON.",
42
+ required: false,
43
+ type: "Boolean"
44
+ })
45
+ markResults?: boolean;
46
+
47
+ constructor(options?: { markResults?: boolean }) {
48
+ super(options);
49
+ this.markResults ??= true;
50
+ }
51
+
52
+ async editorWithData(acc: CraProjects): Promise<TreeVisitor<any, ExecutionContext>> {
53
+ const table = this.dataTable;
54
+ const mark = this.markResults !== false;
55
+ return new class extends JsonVisitor<ExecutionContext> {
56
+ protected override async visitDocument(doc: Json.Document, ctx: ExecutionContext): Promise<Json | undefined> {
57
+ const root = rootObject(doc);
58
+ if (!root) return doc;
59
+ const findings: [Json.Member, Finding][] = [];
60
+ if (isPackageJson(doc.sourcePath)) packageJsonFindings(root, findings);
61
+ else if (isTsConfig(doc.sourcePath) && acc.isCraFile(doc.sourcePath)) tsConfigFindings(root, findings);
62
+ if (findings.length === 0) return doc;
63
+
64
+ for (const [, finding] of findings) table.insertRow(ctx, {filePath: doc.sourcePath, ...finding});
65
+
66
+ // A member that holds several findings, such as `scripts`, carries one marker for the first.
67
+ let changed = false;
68
+ const members = root.members.map(rp => {
69
+ const first = findings.find(([member]) => member === rp.element);
70
+ if (!mark || !first || alreadyMarked(rp.element as Json.Member, first[1].nextStep)) return rp;
71
+ changed = true;
72
+ return {...rp, element: foundSearchResult(rp.element, first[1].nextStep)};
73
+ });
74
+ return changed ? {...doc, value: {...root, members}} as Json.Document : doc;
75
+ }
76
+ };
77
+ }
78
+ }
79
+
80
+ function alreadyMarked(member: Json.Member, description: string): boolean {
81
+ return member.markers.markers.some(m => m.kind === MarkersKind.SearchResult && (m as SearchResult).description === description);
82
+ }
83
+
84
+ function packageJsonFindings(pkg: Json.Object, findings: [Json.Member, Finding][]): void {
85
+ const tool = CONFIG_TOOLS.find(t => hasDependency(pkg, t));
86
+ const isCra = isCraPackage(pkg) || scriptsUseReactScripts(pkg) || !!tool;
87
+ if (!isCra) return;
88
+
89
+ const scripts = memberObject(pkg, "scripts");
90
+ const scriptsMember = getMember(pkg, "scripts");
91
+ if (scripts && scriptsMember) {
92
+ for (const rp of scripts.members) {
93
+ const m = rp.element;
94
+ const command = isMember(m) ? stringValue(m.value) : undefined;
95
+ if (!command || /^react-scripts (start|build)$/.test(command.trim())) continue;
96
+ const name = getMemberKeyName(m as Json.Member);
97
+ const scriptTool = TOOL_SCRIPT.exec(command)?.[2];
98
+ const reactScripts = REACT_SCRIPTS_COMMAND.exec(command)?.[2];
99
+ if (scriptTool) {
100
+ findings.push([scriptsMember, {
101
+ category: "config-override-tool", detail: `script \`${name}\` runs ${scriptTool}`,
102
+ nextStep: `Move the ${scriptTool} overrides into vite.config and replace the \`${name}\` script with vite.`
103
+ }]);
104
+ } else if (reactScripts === "test") {
105
+ findings.push([scriptsMember, {
106
+ category: "jest", detail: `script \`${name}\` runs react-scripts test`,
107
+ nextStep: "Move the tests to Vitest, or keep react-scripts only for tests; Jest cannot read import.meta.env."
108
+ }]);
109
+ } else if (reactScripts) {
110
+ findings.push([scriptsMember, {
111
+ category: "react-scripts-script", detail: `script \`${name}\` runs react-scripts ${reactScripts}`,
112
+ nextStep: reactScripts === "eject" ?
113
+ "Remove the eject script; it has no Vite equivalent." :
114
+ "Rewrite this script by hand: it has flags or wrapping commands the migration does not interpret."
115
+ }]);
116
+ }
117
+ }
118
+ }
119
+
120
+ const dependenciesMember = tool ? ["devDependencies", "dependencies", "optionalDependencies", "peerDependencies"]
121
+ .map(section => ({member: getMember(pkg, section), obj: memberObject(pkg, section)}))
122
+ .find(({obj}) => obj && getMember(obj, tool))?.member : undefined;
123
+ if (tool && dependenciesMember) {
124
+ findings.push([dependenciesMember, {
125
+ category: "config-override-tool", detail: `depends on ${tool}`,
126
+ nextStep: "Re-create the webpack or Babel overrides as Vite config or plugins, then remove the dependency."
127
+ }]);
128
+ }
129
+
130
+ const jest = getMember(pkg, "jest");
131
+ if (jest) {
132
+ findings.push([jest, {
133
+ category: "jest", detail: "jest configuration in package.json",
134
+ nextStep: "Translate the CRA-supported jest keys to Vitest config; react-scripts validated this block."
135
+ }]);
136
+ }
137
+ const eslintConfig = getMember(pkg, "eslintConfig");
138
+ if (eslintConfig && /react-app/.test(printedExtends(eslintConfig))) {
139
+ findings.push([eslintConfig, {
140
+ category: "eslint-config", detail: "eslintConfig extends react-app",
141
+ nextStep: "Keep eslint-config-react-app installed, or move to a standalone ESLint config; Vite does not lint."
142
+ }]);
143
+ }
144
+ const proxy = getMember(pkg, "proxy");
145
+ if (proxy) {
146
+ findings.push([proxy, {
147
+ category: "proxy", detail: "proxy in package.json",
148
+ nextStep: "Configure server.proxy in vite.config; CRA's package.json proxy is not read by Vite."
149
+ }]);
150
+ }
151
+ const homepage = getMember(pkg, "homepage");
152
+ if (homepage) {
153
+ findings.push([homepage, {
154
+ category: "homepage", detail: `homepage ${stringMember(pkg, "homepage") ?? ""}`.trim(),
155
+ nextStep: "Set `base` in vite.config; CRA derived PUBLIC_URL from homepage."
156
+ }]);
157
+ }
158
+ }
159
+
160
+ function tsConfigFindings(root: Json.Object, findings: [Json.Member, Finding][]): void {
161
+ const options = memberObject(root, "compilerOptions");
162
+ const baseUrl = options ? getMember(options, "baseUrl") : undefined;
163
+ const optionsMember = getMember(root, "compilerOptions");
164
+ if (baseUrl && optionsMember) {
165
+ findings.push([optionsMember, {
166
+ category: "absolute-imports", detail: `compilerOptions.baseUrl ${stringMember(options!, "baseUrl") ?? ""}`.trim(),
167
+ nextStep: "Add resolve.alias or vite-tsconfig-paths so imports relative to baseUrl resolve in Vite."
168
+ }]);
169
+ }
170
+ }
171
+
172
+ function printedExtends(eslintConfig: Json.Member): string {
173
+ const value = eslintConfig.value;
174
+ if (value.kind !== Json.Kind.Object) return "";
175
+ const extended = getMember(value as Json.Object, "extends")?.value;
176
+ if (!extended) return "";
177
+ if (extended.kind === Json.Kind.Array) return stringValues(extended as Json.Array).join(",");
178
+ return typeof (extended as Json.Literal).value === "string" ? (extended as Json.Literal).value : "";
179
+ }
@@ -0,0 +1,60 @@
1
+ import {ExecutionContext, TreeVisitor} from "@openrewrite/rewrite";
2
+ import {PlainText, PlainTextVisitor} from "@openrewrite/rewrite/text";
3
+ import {CraProjects, CraScanningRecipe} from "./scan-cra-projects";
4
+ import {craToViteBlockersTable} from "./cra-blockers-table";
5
+ import {isEnvFile} from "./shared";
6
+
7
+ /** Settings that only `react-scripts` reads, with what replaces them in Vite. */
8
+ const CRA_ONLY_SETTINGS = new Map<string, string>([
9
+ ["PORT", "Set `server.port` in vite.config."],
10
+ ["HOST", "Set `server.host` in vite.config."],
11
+ ["HTTPS", "Set `server.https` in vite.config."],
12
+ ["BROWSER", "Set `server.open` in vite.config."],
13
+ ["PUBLIC_URL", "Set `base` in vite.config."],
14
+ ["GENERATE_SOURCEMAP", "Set `build.sourcemap` in vite.config."],
15
+ ["FAST_REFRESH", "Fast refresh is on in `@vitejs/plugin-react`; configure it there."],
16
+ ["INLINE_RUNTIME_CHUNK", "Vite has no runtime chunk; remove the setting."],
17
+ ["IMAGE_INLINE_SIZE_LIMIT", "Set `build.assetsInlineLimit` in vite.config."],
18
+ ["SKIP_PREFLIGHT_CHECK", "Vite has no preflight check; remove the setting."],
19
+ ["TSC_COMPILE_ON_ERROR", "Vite does not type-check; run `tsc --noEmit` separately."],
20
+ ["DISABLE_ESLINT_PLUGIN", "Vite does not lint; remove the setting."],
21
+ ["ESLINT_NO_DEV_ERRORS", "Vite does not lint; remove the setting."],
22
+ ["WDS_SOCKET_HOST", "Set `server.hmr` in vite.config."],
23
+ ["WDS_SOCKET_PATH", "Set `server.hmr` in vite.config."],
24
+ ["WDS_SOCKET_PORT", "Set `server.hmr` in vite.config."],
25
+ ]);
26
+
27
+ /**
28
+ * Finds `.env` settings that only Create React App reads, such as `PORT`, `BROWSER` and `GENERATE_SOURCEMAP`,
29
+ * and records each in a data table with the Vite setting that replaces it. The files are not changed.
30
+ *
31
+ * ```
32
+ * PORT=4000 -> server: {port: 4000} in vite.config
33
+ * ```
34
+ *
35
+ * @see https://vite.dev/config/server-options
36
+ */
37
+ export class FindCraEnvFileBlockers extends CraScanningRecipe {
38
+ readonly name = "org.openrewrite.react.cra-to-vite.find-env-file-blockers";
39
+ readonly displayName = "Find Create React App settings in `.env` files";
40
+ readonly description = "Finds `.env` settings that only `react-scripts` understands, such as `PORT`, `HTTPS`, `BROWSER` and `GENERATE_SOURCEMAP`, and records the Vite setting that replaces each in a data table. The files are not changed.";
41
+
42
+ private dataTable = craToViteBlockersTable();
43
+
44
+ async editorWithData(acc: CraProjects): Promise<TreeVisitor<any, ExecutionContext>> {
45
+ const table = this.dataTable;
46
+ return new class extends PlainTextVisitor<ExecutionContext> {
47
+ protected override async visitText(text: PlainText, ctx: ExecutionContext): Promise<PlainText | undefined> {
48
+ if (!isEnvFile(text.sourcePath) || !acc.isCraFile(text.sourcePath)) return text;
49
+ for (const line of text.text.split("\n")) {
50
+ const name = line.match(/^\s*(?:export\s+)?([A-Z][A-Z0-9_]*)\s*=/)?.[1];
51
+ const nextStep = name ? CRA_ONLY_SETTINGS.get(name) : undefined;
52
+ if (name && nextStep) {
53
+ table.insertRow(ctx, {filePath: text.sourcePath, category: "env-setting", detail: name, nextStep});
54
+ }
55
+ }
56
+ return text;
57
+ }
58
+ };
59
+ }
60
+ }
@@ -0,0 +1,138 @@
1
+ import {check, ExecutionContext, foundSearchResult, not, TreeVisitor} from "@openrewrite/rewrite";
2
+ import {isVendoredOrBundled, JavaScriptVisitor, JS, JSX, namesDeclaredIn} from "@openrewrite/rewrite/javascript";
3
+ import {isIdentifier, J} from "@openrewrite/rewrite/java";
4
+ import {CraProjects, CraScanningRecipe} from "./scan-cra-projects";
5
+ import {baseName, CRA_ENV_PREFIX} from "./shared";
6
+ import {craToViteBlockersTable} from "./cra-blockers-table";
7
+
8
+ const SVG_COMPONENT = "ReactComponent";
9
+ const NODE_SIDE_FILES = new Map<string, [string, string]>([
10
+ ["craco.config", ["config-override-tool", "Re-create the craco overrides as Vite config or plugins."]],
11
+ ["config-overrides", ["config-override-tool", "Re-create the react-app-rewired overrides as Vite config or plugins."]],
12
+ ["setupProxy", ["proxy", "Configure server.proxy in vite.config; Vite does not load src/setupProxy."]],
13
+ ]);
14
+ const SETUP_TESTS = /^setupTests\.[cm]?[jt]sx?$/;
15
+
16
+ /**
17
+ * Finds, in Create React App packages, code that a Create React App to Vite migration does not rewrite and that needs a manual step:
18
+ * `import {ReactComponent} from './logo.svg'`, `require.context`, `module.hot`, `process.env` reads other than
19
+ * `NODE_ENV` and `REACT_APP_*`, JSX in `.js` files, and the `craco.config`, `config-overrides`, `setupProxy`
20
+ * and `setupTests` files.
21
+ *
22
+ * ```ts
23
+ * import {ReactComponent as Logo} from './logo.svg'; // needs vite-plugin-svgr
24
+ * ```
25
+ *
26
+ * @see https://react.dev/blog/2025/02/14/sunsetting-create-react-app#how-to-migrate-to-a-build-tool
27
+ */
28
+ export class FindCraSourceBlockers extends CraScanningRecipe {
29
+ readonly name = "org.openrewrite.react.cra-to-vite.find-source-blockers";
30
+ readonly displayName = "Find Create React App code that needs a manual Vite migration";
31
+ readonly description = "Finds `ReactComponent` SVG imports, `require.context`, `module.hot`, `process.env` reads that Vite does not define, JSX in `.js` files, and `craco`, `react-app-rewired`, `setupProxy` and `setupTests` files, and records each in a data table.";
32
+
33
+ private dataTable = craToViteBlockersTable();
34
+
35
+ async editorWithData(acc: CraProjects): Promise<TreeVisitor<any, ExecutionContext>> {
36
+ const table = this.dataTable;
37
+ return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
38
+ private filePath = "";
39
+ private jsxReported = false;
40
+ private globalProcess = true;
41
+
42
+ private report(ctx: ExecutionContext, category: string, detail: string, nextStep: string) {
43
+ table.insertRow(ctx, {filePath: this.filePath, category, detail, nextStep});
44
+ }
45
+
46
+ override async visitJsCompilationUnit(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<J | undefined> {
47
+ if (!acc.isCraFile(cu.sourcePath)) return cu;
48
+ this.filePath = cu.sourcePath;
49
+ this.jsxReported = false;
50
+ this.globalProcess = !namesDeclaredIn(cu).has("process");
51
+ const visited = await super.visitJsCompilationUnit(cu, ctx) as JS.CompilationUnit;
52
+ const stem = baseName(cu.sourcePath).replace(/\.[cm]?[jt]sx?$/, "");
53
+ const nodeSide = NODE_SIDE_FILES.get(stem);
54
+ if (nodeSide) {
55
+ this.report(ctx, nodeSide[0], baseName(cu.sourcePath), nodeSide[1]);
56
+ return foundSearchResult(visited, nodeSide[1]);
57
+ }
58
+ if (SETUP_TESTS.test(baseName(cu.sourcePath))) {
59
+ const step = "Move this Jest setup file to Vitest's `setupFiles`.";
60
+ this.report(ctx, "jest", baseName(cu.sourcePath), step);
61
+ return foundSearchResult(visited, step);
62
+ }
63
+ return visited;
64
+ }
65
+
66
+ override async visitImportDeclaration(jsImport: JS.Import, ctx: ExecutionContext): Promise<J | undefined> {
67
+ const visited = await super.visitImportDeclaration(jsImport, ctx) as JS.Import;
68
+ const module = visited.moduleSpecifier?.element as J.Literal | undefined;
69
+ const path = typeof module?.value === "string" ? module.value : undefined;
70
+ if (!path || !/\.svg(\?.*)?$/.test(path) || !importsReactComponent(visited)) return visited;
71
+ const step = "Add `vite-plugin-svgr` and import `Logo from './logo.svg?react'`; Vite has no `ReactComponent` export.";
72
+ this.report(ctx, "svg-react-component", `import ${SVG_COMPONENT} from '${path}'`, step);
73
+ return foundSearchResult(visited, step);
74
+ }
75
+
76
+ override async visitMethodInvocation(method: J.MethodInvocation, ctx: ExecutionContext): Promise<J | undefined> {
77
+ const visited = await super.visitMethodInvocation(method, ctx) as J.MethodInvocation;
78
+ const select = visited.select?.element;
79
+ if (visited.name.simpleName === "context" && select && isIdentifier(select) && select.simpleName === "require") {
80
+ const step = "Use `import.meta.glob`, which Vite provides instead of webpack's `require.context`.";
81
+ this.report(ctx, "require-context", "require.context", step);
82
+ return foundSearchResult(visited, step);
83
+ }
84
+ return visited;
85
+ }
86
+
87
+ override async visitFieldAccess(fieldAccess: J.FieldAccess, ctx: ExecutionContext): Promise<J | undefined> {
88
+ const visited = await super.visitFieldAccess(fieldAccess, ctx) as J.FieldAccess;
89
+ const name = visited.name.element.simpleName;
90
+ if (isIdentifier(visited.target) && visited.target.simpleName === "module" && name === "hot") {
91
+ const step = "Use `import.meta.hot`; Vite's HMR API replaces webpack's `module.hot`.";
92
+ this.report(ctx, "hot-module-replacement", "module.hot", step);
93
+ return foundSearchResult(visited, step);
94
+ }
95
+ if (this.isProcessEnv(visited) && !this.isMigratedEnvRead(this.cursor.parent?.value)) {
96
+ const step = "Vite only exposes `import.meta.env.VITE_*` and replaces `process.env.NODE_ENV`; read this value from `import.meta.env`.";
97
+ this.report(ctx, "process-env", "process.env access that is not process.env.REACT_APP_* or NODE_ENV", step);
98
+ return foundSearchResult(visited, step);
99
+ }
100
+ return visited;
101
+ }
102
+
103
+ override async visitJsxTag(tag: JSX.Tag, ctx: ExecutionContext): Promise<J | undefined> {
104
+ // Claim the file before visiting the children, so the outermost tag is the one marked.
105
+ const report = !this.jsxReported && /\.[cm]?js$/.test(this.filePath);
106
+ if (report) this.jsxReported = true;
107
+ const visited = await super.visitJsxTag(tag, ctx);
108
+ if (!report) return visited;
109
+ const step = "Rename the file to `.jsx`; `@vitejs/plugin-react` only transforms JSX in `.jsx` and `.tsx` files.";
110
+ this.report(ctx, "jsx-in-js-file", baseName(this.filePath), step);
111
+ return foundSearchResult(visited as JSX.Tag, step);
112
+ }
113
+
114
+ private isProcessEnv(expr: J.FieldAccess): boolean {
115
+ return this.globalProcess && expr.name.element.simpleName === "env" &&
116
+ isIdentifier(expr.target) && expr.target.simpleName === "process";
117
+ }
118
+
119
+ /** `process.env.REACT_APP_X` and `process.env.NODE_ENV` are handled; any other use of `process.env` is not. */
120
+ private isMigratedEnvRead(parent: unknown): boolean {
121
+ const access = parent as J.FieldAccess | undefined;
122
+ if (!access || access.kind !== J.Kind.FieldAccess) return false;
123
+ const name = access.name.element.simpleName;
124
+ return name === "NODE_ENV" || name.startsWith(CRA_ENV_PREFIX);
125
+ }
126
+ });
127
+ }
128
+ }
129
+
130
+ function importsReactComponent(jsImport: JS.Import): boolean {
131
+ const bindings = jsImport.importClause?.namedBindings;
132
+ if (!bindings || bindings.kind !== JS.Kind.NamedImports) return false;
133
+ return (bindings as JS.NamedImports).elements.elements.some(rp => {
134
+ const specifier = (rp.element as JS.ImportSpecifier).specifier;
135
+ const imported = specifier.kind === JS.Kind.Alias ? (specifier as JS.Alias).propertyName.element : specifier;
136
+ return isIdentifier(imported) && imported.simpleName === SVG_COMPONENT;
137
+ });
138
+ }
@@ -0,0 +1,21 @@
1
+ import {Recipe} from "@openrewrite/rewrite";
2
+ import {FindCraConfigBlockers} from "./find-cra-config-blockers";
3
+ import {FindCraSourceBlockers} from "./find-cra-source-blockers";
4
+ import {FindCraEnvFileBlockers} from "./find-cra-env-file-blockers";
5
+
6
+ /**
7
+ * Finds everything in a Create React App project that the Vite migration does not rewrite, and records it in
8
+ * the `CraToViteBlockers` data table: `craco` and `react-app-rewired`, Jest configuration, `ReactComponent` SVG
9
+ * imports, `require.context`, `module.hot`, `proxy` and `homepage`, JSX in `.js` files and CRA-only `.env` settings.
10
+ *
11
+ * @see https://react.dev/blog/2025/02/14/sunsetting-create-react-app#how-to-migrate-to-a-build-tool
12
+ */
13
+ export class FindCraToViteBlockers extends Recipe {
14
+ readonly name = "org.openrewrite.react.cra-to-vite.find-blockers";
15
+ readonly displayName = "Find Create React App to Vite migration blockers";
16
+ readonly description = "Finds the Create React App features that have no automatic Vite equivalent, such as `craco`, Jest configuration, `ReactComponent` SVG imports and `proxy` settings, and records them in a data table with the manual step each needs.";
17
+
18
+ async recipeList(): Promise<Recipe[]> {
19
+ return [new FindCraConfigBlockers(), new FindCraSourceBlockers(), new FindCraEnvFileBlockers()];
20
+ }
21
+ }
@@ -0,0 +1,26 @@
1
+ import {AddViteConfig} from "./add-vite-config";
2
+ import {FindCraConfigBlockers} from "./find-cra-config-blockers";
3
+ import {FindCraEnvFileBlockers} from "./find-cra-env-file-blockers";
4
+ import {FindCraSourceBlockers} from "./find-cra-source-blockers";
5
+ import {FindCraToViteBlockers} from "./find-cra-to-vite-blockers";
6
+ import {MovePublicIndexHtml} from "./move-public-index-html";
7
+ import {RenameProcessEnvReactApp} from "./rename-process-env-react-app";
8
+ import {RenameReactAppEnvVarsInEnvFiles} from "./rename-react-app-env-vars-in-env-files";
9
+ import {ReplaceReactScriptsDependency} from "./replace-react-scripts-dependency";
10
+ import {UpdateReactAppEnvTypes} from "./update-react-app-env-types";
11
+ import {UpdateReactScriptsScripts} from "./update-react-scripts-scripts";
12
+ import {UpdateTsconfigForVite} from "./update-tsconfig-for-vite";
13
+
14
+ export {CraToVite} from "./cra-to-vite";
15
+ export {
16
+ AddViteConfig, FindCraConfigBlockers, FindCraEnvFileBlockers, FindCraSourceBlockers, FindCraToViteBlockers,
17
+ MovePublicIndexHtml, RenameProcessEnvReactApp, RenameReactAppEnvVarsInEnvFiles, ReplaceReactScriptsDependency,
18
+ UpdateReactAppEnvTypes, UpdateReactScriptsScripts, UpdateTsconfigForVite,
19
+ };
20
+
21
+ /** The recipes `CraToVite` is made of, which are installed in the marketplace next to it. */
22
+ export const craToViteRecipes = [
23
+ UpdateReactScriptsScripts, ReplaceReactScriptsDependency, AddViteConfig, MovePublicIndexHtml,
24
+ RenameReactAppEnvVarsInEnvFiles, RenameProcessEnvReactApp, UpdateReactAppEnvTypes, UpdateTsconfigForVite,
25
+ FindCraToViteBlockers, FindCraConfigBlockers, FindCraSourceBlockers, FindCraEnvFileBlockers,
26
+ ];
@@ -0,0 +1,132 @@
1
+ import {ExecutionContext, Parsers, SourceFile, TreeVisitor} from "@openrewrite/rewrite";
2
+ import {PlainText, PlainTextVisitor} from "@openrewrite/rewrite/text";
3
+ import {CraProjects, CraScanningRecipe, indexHtmlRoot} from "./scan-cra-projects";
4
+ import {craToViteBlockersTable} from "./cra-blockers-table";
5
+ import {CRA_ENV_PREFIX, joinPath, VITE_ENV_PREFIX} from "./shared";
6
+
7
+ const ENTRY_FILES = ["src/index.tsx", "src/index.ts", "src/index.jsx", "src/index.js"];
8
+ // CRA placeholders are upper case; `%20` and other percent-encoded URLs are not.
9
+ const PLACEHOLDER = /%([A-Z][A-Z0-9_]*)%/g;
10
+
11
+ /**
12
+ * The text of the root `index.html` Vite needs, or `undefined` when the page is not safe to move:
13
+ * it holds a `%...%` placeholder other than `%PUBLIC_URL%` and `%REACT_APP_*%`, or already loads the entry file.
14
+ */
15
+ export function viteIndexHtml(html: string, entry: string): string | undefined {
16
+ for (const [, name] of html.matchAll(PLACEHOLDER)) {
17
+ if (name !== "PUBLIC_URL" && !name.startsWith(CRA_ENV_PREFIX)) return undefined;
18
+ }
19
+ if (html.includes(`/${entry}`) || !html.includes("</body>")) return undefined;
20
+ const migrated = html
21
+ .replace(/%PUBLIC_URL%(?=\/)/g, "")
22
+ .replace(/%PUBLIC_URL%/g, "/")
23
+ .replace(/%REACT_APP_([A-Za-z0-9_]+)%/g, `%${VITE_ENV_PREFIX}$1%`);
24
+ const script = `<script type="module" src="/${entry}"></script>`;
25
+ return migrated.replace(/([ \t]*)<\/body>/, (_match, indent, offset) =>
26
+ offset === 0 || migrated[offset - 1] === "\n" ?
27
+ `${indent} ${script}\n${indent}</body>` : `\n${script}\n</body>`);
28
+ }
29
+
30
+ interface Plan {
31
+ moved: Map<string, string>;
32
+ declined: Map<string, {reason: string; entry?: string}>;
33
+ /** Roots whose `public/index.html` is not in the LST, so it can be neither moved nor checked. */
34
+ missing: Map<string, string>;
35
+ }
36
+
37
+ /** The scan is finished before the edit and generate phases run, so each one's plan is computed once. */
38
+ const plans = new WeakMap<CraProjects, Plan>();
39
+
40
+ /** Roots whose `public/index.html` can move, and why the others stay. */
41
+ function plan(acc: CraProjects): Plan {
42
+ let cached = plans.get(acc);
43
+ if (!cached) plans.set(acc, cached = computePlan(acc));
44
+ return cached;
45
+ }
46
+
47
+ function computePlan(acc: CraProjects): Plan {
48
+ const moved = new Map<string, string>();
49
+ const declined = new Map<string, {reason: string; entry?: string}>();
50
+ const missing = new Map<string, string>();
51
+ for (const root of acc.viteRoots) {
52
+ const html = acc.indexHtml.get(root);
53
+ const entry = acc.firstExisting(root, ENTRY_FILES);
54
+ if (html === undefined) {
55
+ if (!acc.has(root, "index.html")) missing.set(root, entry ?? "src/index.tsx");
56
+ continue;
57
+ }
58
+ if (acc.has(root, "index.html")) {
59
+ declined.set(root, {reason: "The project already has an index.html at its root.", entry});
60
+ } else if (entry === undefined) {
61
+ declined.set(root, {reason: "No src/index.tsx, .ts, .jsx or .js entry file was found to point the module script at."});
62
+ } else {
63
+ const migrated = viteIndexHtml(html, entry);
64
+ if (migrated === undefined) {
65
+ declined.set(root, {reason: "The page uses a placeholder other than %PUBLIC_URL% and %REACT_APP_*%, already loads the entry, or has no </body>.", entry});
66
+ } else {
67
+ moved.set(root, migrated);
68
+ }
69
+ }
70
+ }
71
+ return {moved, declined, missing};
72
+ }
73
+
74
+ /**
75
+ * Moves `public/index.html` to the project root, where Vite looks for it, and adds the module script for
76
+ * the entry file.
77
+ *
78
+ * ```html
79
+ * <link rel="icon" href="%PUBLIC_URL%/favicon.ico" /> -> <link rel="icon" href="/favicon.ico" />
80
+ * </body> -> <script type="module" src="/src/index.tsx"></script></body>
81
+ * ```
82
+ *
83
+ * `%PUBLIC_URL%/` becomes `/`, which Vite serves from `public/`, and `%REACT_APP_*%` becomes `%VITE_*%`.
84
+ * The page stays where it is when the project already has a root `index.html`, has no `src/index.*` entry
85
+ * file, or uses a placeholder Vite does not know, and the blockers data table says which. A package whose `public/index.html` is not in the LST is recorded too.
86
+ *
87
+ * @see https://vite.dev/guide/#index-html-and-project-root
88
+ */
89
+ export class MovePublicIndexHtml extends CraScanningRecipe {
90
+ readonly name = "org.openrewrite.react.cra-to-vite.move-public-index-html";
91
+ readonly displayName = "Move `public/index.html` to the project root for Vite";
92
+ readonly description = "Moves `public/index.html` of a Create React App project to the project root, replaces `%PUBLIC_URL%` and `%REACT_APP_*%` placeholders, and adds a module script for `src/index`. Pages that cannot be moved safely are left in place.";
93
+
94
+ async editorWithData(acc: CraProjects): Promise<TreeVisitor<any, ExecutionContext>> {
95
+ const {moved, declined} = plan(acc);
96
+ // The edit only asks which roots move, so it does not need to keep each page's migrated text.
97
+ const movedRoots = new Set(moved.keys());
98
+ const table = craToViteBlockersTable();
99
+ return new class extends PlainTextVisitor<ExecutionContext> {
100
+ protected override async visitText(text: PlainText, ctx: ExecutionContext): Promise<PlainText | undefined> {
101
+ const root = indexHtmlRoot(text.sourcePath);
102
+ if (root === undefined) return text;
103
+ const declination = declined.get(root);
104
+ if (declination !== undefined) {
105
+ const {reason, entry} = declination;
106
+ table.insertRow(ctx, {
107
+ filePath: text.sourcePath, category: "index-html", detail: "public/index.html was not moved",
108
+ nextStep: `${reason} Move it to the project root by hand and add <script type="module" src="/${entry ?? "src/index.tsx"}"></script>.`
109
+ });
110
+ }
111
+ return movedRoots.has(root) ? undefined : text;
112
+ }
113
+ };
114
+ }
115
+
116
+ async generate(acc: CraProjects, ctx: ExecutionContext): Promise<SourceFile[]> {
117
+ const parser = Parsers.createParser("plainText", {ctx});
118
+ const generated: SourceFile[] = [];
119
+ const table = craToViteBlockersTable();
120
+ for (const [root, entry] of plan(acc).missing) {
121
+ // Only the path is recorded: the page may exist but not be in the LST, since `.html` is not always loaded.
122
+ table.insertRow(ctx, {
123
+ filePath: joinPath(root, "package.json"), category: "index-html", detail: "public/index.html was not found in the LST",
124
+ nextStep: `Vite needs index.html at the project root, and \`vite build\` fails without it. Move public/index.html there by hand and add <script type="module" src="/${entry}"></script>.`
125
+ });
126
+ }
127
+ for (const [root, html] of plan(acc).moved) {
128
+ generated.push(await parser.parseOne({text: html, sourcePath: joinPath(root, "index.html")}));
129
+ }
130
+ return generated;
131
+ }
132
+ }
@@ -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
+ }