* Run the React Compiler over a single file and return the number of * successfully compiled functions plus any diagnostics. Transform * errors are caught and returned as a diagnostic with line 0 rather * than thrown, so the caller always gets a result.
(file)
| 125 | * than thrown, so the caller always gets a result. |
| 126 | */ |
| 127 | function compileFile(file) { |
| 128 | const isTSX = file.endsWith(".tsx"); |
| 129 | const diagnostics = []; |
| 130 | |
| 131 | try { |
| 132 | const code = readFileSync(join(siteDir, file), "utf-8"); |
| 133 | const result = transformSync(code, { |
| 134 | plugins: [ |
| 135 | ["@babel/plugin-syntax-typescript", { isTSX }], |
| 136 | ["babel-plugin-react-compiler", { |
| 137 | logger: { |
| 138 | logEvent(_filename, event) { |
| 139 | if (event.kind === "CompileError" || event.kind === "CompileSkip") { |
| 140 | const msg = event.detail || event.reason || "(unknown)"; |
| 141 | diagnostics.push({ |
| 142 | line: event.fnLoc?.start?.line ?? 0, |
| 143 | short: shortenMessage(msg), |
| 144 | }); |
| 145 | } |
| 146 | }, |
| 147 | }, |
| 148 | }], |
| 149 | ], |
| 150 | filename: file, |
| 151 | // Skip config-file resolution. No babel.config.js exists in the |
| 152 | // repo, so the search is wasted I/O on every file. |
| 153 | configFile: false, |
| 154 | babelrc: false, |
| 155 | }); |
| 156 | |
| 157 | // The compiler inserts `const $ = _c(N)` at the top of every |
| 158 | // function it successfully compiles, where N is the number of |
| 159 | // memoization slots. Counting these tells us how many functions |
| 160 | // were compiled in this file. |
| 161 | const compiledCount = result?.code?.match(/const \$ = _c\(\d+\)/g)?.length ?? 0; |
| 162 | |
| 163 | return { |
| 164 | compiled: compiledCount, |
| 165 | code: result?.code ?? "", |
| 166 | diagnostics: deduplicateDiagnostics(diagnostics), |
| 167 | }; |
| 168 | } catch (e) { |
| 169 | return { |
| 170 | compiled: 0, |
| 171 | code: "", |
| 172 | diagnostics: [{ |
| 173 | line: 0, |
| 174 | // Truncate to keep the one-line report readable. |
| 175 | short: `Transform error: ${(e instanceof Error ? e.message : String(e)).substring(0, MAX_ERROR_LENGTH)}`, |
| 176 | }], |
| 177 | }; |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | // --------------------------------------------------------------------------- |
| 182 | // Scope-pruning detection |
no test coverage detected