Update HMR. Make it true HMR. Add URL to page server props

This commit is contained in:
2026-03-20 11:19:22 +01:00
parent 7804a34951
commit 52dde6c0ab
52 changed files with 1548 additions and 708 deletions
+18 -70
View File
@@ -1,56 +1,23 @@
import { existsSync, writeFileSync } from "fs";
import path from "path";
import { writeFileSync } from "fs";
import * as esbuild from "esbuild";
import postcss from "postcss";
import tailwindcss from "@tailwindcss/postcss";
import { readFile } from "fs/promises";
import grabAllPages from "../../utils/grab-all-pages";
import grabDirNames from "../../utils/grab-dir-names";
import AppNames from "../../utils/grab-app-names";
import isDevelopment from "../../utils/is-development";
import { execSync } from "child_process";
import grabConstants from "../../utils/grab-constants";
import { log } from "../../utils/log";
const { HYDRATION_DST_DIR, PAGES_DIR, HYDRATION_DST_DIR_MAP_JSON_FILE } = grabDirNames();
const tailwindPlugin = {
name: "tailwindcss",
setup(build) {
build.onLoad({ filter: /\.css$/ }, async (args) => {
const source = await readFile(args.path, "utf-8");
const result = await postcss([tailwindcss()]).process(source, {
from: args.path,
});
return {
contents: result.css,
loader: "css",
};
});
},
};
import tailwindEsbuildPlugin from "../server/web-pages/tailwind-esbuild-plugin";
import grabClientHydrationScript from "./grab-client-hydration-script";
import grabArtifactsFromBundledResults from "./grab-artifacts-from-bundled-result";
const { HYDRATION_DST_DIR, HYDRATION_DST_DIR_MAP_JSON_FILE } = grabDirNames();
export default async function allPagesBundler(params) {
const pages = grabAllPages({ exclude_api: true });
const { ClientRootElementIDName, ClientRootComponentWindowName } = grabConstants();
const virtualEntries = {};
const dev = isDevelopment();
const root_component_path = path.join(PAGES_DIR, `${AppNames["RootPagesComponentName"]}.tsx`);
const does_root_exist = existsSync(root_component_path);
for (const page of pages) {
const key = page.local_path;
let txt = ``;
txt += `import { hydrateRoot } from "react-dom/client";\n`;
if (does_root_exist) {
txt += `import Root from "${root_component_path}";\n`;
}
txt += `import Page from "${page.local_path}";\n\n`;
txt += `const pageProps = window.__PAGE_PROPS__ || {};\n`;
if (does_root_exist) {
txt += `const component = <Root {...pageProps}><Page {...pageProps} /></Root>\n`;
}
else {
txt += `const component = <Page {...pageProps} />\n`;
}
txt += `const root = hydrateRoot(document.getElementById("${ClientRootElementIDName}"), component);\n\n`;
txt += `window.${ClientRootComponentWindowName} = root;\n`;
const txt = grabClientHydrationScript({
page_local_path: page.local_path,
});
virtualEntries[key] = txt;
}
const virtualPlugin = {
@@ -77,38 +44,18 @@ export default async function allPagesBundler(params) {
build.onEnd((result) => {
if (result.errors.length > 0)
return;
const artifacts = Object.entries(result.metafile.outputs)
.filter(([, meta]) => meta.entryPoint)
.map(([outputPath, meta]) => {
const target_page = pages.find((p) => {
return (meta.entryPoint === `virtual:${p.local_path}`);
});
if (!target_page || !meta.entryPoint) {
return undefined;
}
const { file_name, local_path, url_path } = target_page;
const cssPath = meta.cssBundle || undefined;
return {
path: outputPath,
hash: path.basename(outputPath, path.extname(outputPath)),
type: outputPath.endsWith(".css")
? "text/css"
: "text/javascript",
entrypoint: meta.entryPoint,
css_path: cssPath,
file_name,
local_path,
url_path,
};
const artifacts = grabArtifactsFromBundledResults({
pages,
result,
});
if (artifacts.length > 0) {
const final_artifacts = artifacts.filter((a) => Boolean(a?.entrypoint));
global.BUNDLER_CTX_MAP = final_artifacts;
params?.post_build_fn?.({ artifacts: final_artifacts });
if (artifacts?.[0] && artifacts.length > 0) {
global.BUNDLER_CTX_MAP = artifacts;
global.PAGE_FILES = pages;
params?.post_build_fn?.({ artifacts });
writeFileSync(HYDRATION_DST_DIR_MAP_JSON_FILE, JSON.stringify(artifacts));
}
const elapsed = (performance.now() - buildStart).toFixed(0);
log.success(`Built in ${elapsed}ms`);
log.success(`[Built] in ${elapsed}ms`);
if (params?.exit_after_first_build) {
process.exit();
}
@@ -129,9 +76,10 @@ export default async function allPagesBundler(params) {
},
entryNames: "[dir]/[name]/[hash]",
metafile: true,
plugins: [tailwindPlugin, virtualPlugin, artifactTracker],
plugins: [tailwindEsbuildPlugin, virtualPlugin, artifactTracker],
jsx: "automatic",
splitting: true,
logLevel: "silent",
});
await ctx.rebuild();
if (params?.watch) {
@@ -0,0 +1,35 @@
import path from "path";
import * as esbuild from "esbuild";
export default function grabArtifactsFromBundledResults({ result, pages, }) {
if (result.errors.length > 0)
return;
const artifacts = Object.entries(result.metafile.outputs)
.filter(([, meta]) => meta.entryPoint)
.map(([outputPath, meta]) => {
const target_page = pages.find((p) => {
return meta.entryPoint === `virtual:${p.local_path}`;
});
if (!target_page || !meta.entryPoint) {
return undefined;
}
const { file_name, local_path, url_path } = target_page;
const cssPath = meta.cssBundle || undefined;
return {
path: outputPath,
hash: path.basename(outputPath, path.extname(outputPath)),
type: outputPath.endsWith(".css")
? "text/css"
: "text/javascript",
entrypoint: meta.entryPoint,
css_path: cssPath,
file_name,
local_path,
url_path,
};
});
if (artifacts.length > 0) {
const final_artifacts = artifacts.filter((a) => Boolean(a?.entrypoint));
return final_artifacts;
}
return undefined;
}
+65
View File
@@ -0,0 +1,65 @@
import { existsSync } from "fs";
import path from "path";
import grabDirNames from "../../utils/grab-dir-names";
import AppNames from "../../utils/grab-app-names";
import grabConstants from "../../utils/grab-constants";
const { PAGES_DIR } = grabDirNames();
export default function grabClientHydrationScript({ page_local_path }) {
const { ClientRootElementIDName, ClientRootComponentWindowName } = grabConstants();
const root_component_path = path.join(PAGES_DIR, `${AppNames["RootPagesComponentName"]}.tsx`);
const does_root_exist = existsSync(root_component_path);
// let txt = ``;
// txt += `import { hydrateRoot } from "react-dom/client";\n`;
// if (does_root_exist) {
// txt += `import Root from "${root_component_path}";\n`;
// }
// txt += `import Page from "${page.local_path}";\n\n`;
// txt += `const pageProps = window.__PAGE_PROPS__ || {};\n`;
// if (does_root_exist) {
// txt += `const component = <Root {...pageProps}><Page {...pageProps} /></Root>\n`;
// } else {
// txt += `const component = <Page {...pageProps} />\n`;
// }
// txt += `const root = hydrateRoot(document.getElementById("${ClientRootElementIDName}"), component);\n\n`;
// txt += `window.${ClientRootComponentWindowName} = root;\n`;
let txt = ``;
// txt += `import * as React from "react";\n`;
// txt += `import * as ReactDOM from "react-dom";\n`;
// txt += `import * as ReactDOMClient from "react-dom/client";\n`;
// txt += `import * as JSXRuntime from "react/jsx-runtime";\n`;
txt += `import { hydrateRoot, createElement } from "react-dom/client";\n`;
if (does_root_exist) {
txt += `import Root from "${root_component_path}";\n`;
}
txt += `import Page from "${page_local_path}";\n\n`;
// txt += `window.__REACT__ = React;\n`;
// txt += `window.__REACT_DOM__ = ReactDOM;\n`;
// txt += `window.__REACT_DOM_CLIENT__ = ReactDOMClient;\n`;
// txt += `window.__JSX_RUNTIME__ = JSXRuntime;\n\n`;
txt += `const pageProps = window.__PAGE_PROPS__ || {};\n`;
if (does_root_exist) {
txt += `const component = <Root {...pageProps}><Page {...pageProps} /></Root>\n`;
}
else {
txt += `const component = <Page {...pageProps} />\n`;
}
txt += `if (window.${ClientRootComponentWindowName}?.render) {\n`;
txt += ` window.${ClientRootComponentWindowName}.render(component);\n`;
txt += `} else {\n`;
txt += ` const root = hydrateRoot(document.getElementById("${ClientRootElementIDName}"), component);\n\n`;
txt += ` window.${ClientRootComponentWindowName} = root;\n`;
txt += ` window.__BUNEXT_RERENDER__ = (NewPage) => {\n`;
txt += ` const props = window.__PAGE_PROPS__ || {};\n`;
txt += ` root.render(<NewPage {...props} />);\n`;
txt += ` };\n`;
txt += `}\n`;
// // HMR re-render helper
// if (does_root_exist) {
// txt += `window.__BUNEXT_RERENDER__ = (NewPage) => {\n`;
// txt += ` const props = window.__PAGE_PROPS__ || {};\n`;
// txt += ` root.render(<Root {...props}><NewPage {...props} /></Root>);\n`;
// txt += `};\n`;
// } else {
// }
return txt;
}