compileReact
uses node:crypto
A component module (code, of a cache module for code written against React jsx, as npm:react@19) as React
Compiler makes it: its components and hooks memoized, so a re-render does only what changed. oxc's port of it
(reactCompiler), as a tool tcm installs the first time it's needed, as it does oxlint. Kept in .tcm/compiled by the module's text and the
compiler's version, so each version of a module is compiled once. development is for a dev server's modules. Undefined when the compiler can't take the module
(it then stays as written: what React Compiler can't make sure of, it leaves alone, as it does a component that says
"use no memo").
import type { Codebase } from "#codebase/tcmts/cli/codebase"; import { reactCompiler } from "#codebase/tcmts/cli/web"; import { npmAlias } from "#codebase/tcmts/loader/packages"; import { createHash } from "node:crypto"; import fs from "node:fs"; import path from "node:path"; export function compileReact( cb: Codebase, file: string, code: string, jsx: string, development = false, ): string | undefined { const compiler = reactCompiler(cb); // (by this code's hash too: another tcm compiles them again) const by = (compileReact as unknown as Record<symbol, string | undefined>)[Symbol.for("tcm.hash")] ?? ""; const key = createHash("sha256") .update(`${by}\n${compiler.version}\n${jsx}\n${development}\n${code}`) .digest("hex") .slice(0, 32); const kept = path.join(cb.lay.tcmDir, "compiled", `${key}.js`); if (fs.existsSync(kept)) return fs.readFileSync(kept, "utf8") || undefined; let out = ""; try { const r = compiler.transformSync(file, code, { reactCompiler: { target: jsx.slice(jsx.lastIndexOf("@") + 1) }, // (in development, JSX as Vite's server has it: `jsx-dev-runtime`, the import its scan of the source found) jsx: { runtime: "automatic", development }, }); // (its runtime is the React the module renders with, as that React has it: `react/compiler-runtime` asks for // React by its own name, which a bundler can make another copy) if (!r.fatal && !r.errors.length) out = r.code.replace( /import \{ c as (\w+) \} from "react\/compiler-runtime";/, (_, local: string) => // (read from the module, or from what CommonJS exports: a bundler's ESM of React may not name it) `import * as __tcm_react from ${JSON.stringify(npmAlias(jsx))};\nconst ${local} = (__tcm_react.__COMPILER_RUNTIME ?? __tcm_react.default.__COMPILER_RUNTIME).c;`, ); if (out.includes("react/compiler-runtime")) out = ""; } catch { out = ""; } fs.mkdirSync(path.dirname(kept), { recursive: true }); fs.writeFileSync(kept, out); return out || undefined; }