Bugfix. Extract react imports from main bundler to vendor static files
This commit is contained in:
@@ -16,8 +16,6 @@ type Params = {
|
||||
};
|
||||
|
||||
export default async function allPagesESBuildContextBundler(params?: Params) {
|
||||
// return await allPagesESBuildContextBundlerFiles(params);
|
||||
|
||||
const pages = grabAllPages({ exclude_api: true });
|
||||
|
||||
global.PAGE_FILES = pages;
|
||||
@@ -62,6 +60,7 @@ export default async function allPagesESBuildContextBundler(params?: Params) {
|
||||
entryNames: "[dir]/[hash]",
|
||||
metafile: true,
|
||||
plugins: [
|
||||
forceExternalReact(),
|
||||
tailwindEsbuildPlugin,
|
||||
virtualFilesPlugin({
|
||||
entryToPage,
|
||||
@@ -74,18 +73,29 @@ export default async function allPagesESBuildContextBundler(params?: Params) {
|
||||
jsx: "automatic",
|
||||
splitting: true,
|
||||
treeShaking: true,
|
||||
logLevel: "silent",
|
||||
// logLevel: "silent",
|
||||
// logLevel: dev ? "error" : "silent",
|
||||
// external: [
|
||||
// "react",
|
||||
// "react-dom",
|
||||
// "react-dom/client",
|
||||
// "react/jsx-runtime",
|
||||
// "react/jsx-dev-runtime",
|
||||
// ],
|
||||
// jsxDev: dev,
|
||||
external: [
|
||||
"react",
|
||||
"react-dom",
|
||||
"react-dom/client",
|
||||
"react/jsx-runtime",
|
||||
"react/jsx-dev-runtime",
|
||||
],
|
||||
});
|
||||
|
||||
await global.BUNDLER_CTX.rebuild();
|
||||
}
|
||||
|
||||
function forceExternalReact(): esbuild.Plugin {
|
||||
return {
|
||||
name: "force-external-react",
|
||||
setup(build) {
|
||||
build.onResolve({ filter: /^react(-dom)?(\/.*)?$/ }, (args) => {
|
||||
if (args.pluginData?.externalReact) return null;
|
||||
return {
|
||||
path: args.path,
|
||||
external: true,
|
||||
};
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import grabDirNames from "../../utils/grab-dir-names";
|
||||
import isDevelopment from "../../utils/is-development";
|
||||
import path from "path";
|
||||
import { rmSync, mkdirSync, writeFileSync } from "fs";
|
||||
|
||||
const { BUNEXT_VENDOR_DIR, BUNX_CWD_DIR } = grabDirNames();
|
||||
|
||||
const VENDOR_ENTRIES: Record<string, string> = {
|
||||
react: `
|
||||
import React from "react";
|
||||
export const {
|
||||
Children, Component, Fragment, Profiler, PureComponent, StrictMode,
|
||||
Suspense, cloneElement, createContext, createElement, createRef,
|
||||
forwardRef, isValidElement, lazy, memo, startTransition,
|
||||
useCallback, useContext, useDebugValue, useDeferredValue, useEffect,
|
||||
useId, useImperativeHandle, useInsertionEffect, useLayoutEffect,
|
||||
useMemo, useReducer, useRef, useState, useSyncExternalStore,
|
||||
useTransition, version, use, cache, act,
|
||||
} = React;
|
||||
export default React;
|
||||
`,
|
||||
"react-dom": `
|
||||
import ReactDOM from "react-dom";
|
||||
export const {
|
||||
createPortal, flushSync, version,
|
||||
} = ReactDOM;
|
||||
export default ReactDOM;
|
||||
`,
|
||||
"react-dom_client": `
|
||||
import ReactDOMClient from "react-dom/client";
|
||||
export const { createRoot, hydrateRoot } = ReactDOMClient;
|
||||
export default ReactDOMClient;
|
||||
`,
|
||||
"react_jsx-runtime": `
|
||||
import JSXRuntime from "react/jsx-runtime";
|
||||
export const { jsx, jsxs, Fragment } = JSXRuntime;
|
||||
`,
|
||||
"react_jsx-dev-runtime": `
|
||||
import JSXDevRuntime from "react/jsx-dev-runtime";
|
||||
export const { jsxDEV, Fragment } = JSXDevRuntime;
|
||||
`,
|
||||
};
|
||||
|
||||
export default async function bunReactModulesBundler() {
|
||||
const dev = isDevelopment();
|
||||
|
||||
rmSync(BUNEXT_VENDOR_DIR, { force: true, recursive: true });
|
||||
|
||||
const tmpDir = path.join(BUNEXT_VENDOR_DIR, "_tmp");
|
||||
mkdirSync(tmpDir, { recursive: true });
|
||||
|
||||
const entrypoints: string[] = [];
|
||||
for (const [name, contents] of Object.entries(VENDOR_ENTRIES)) {
|
||||
const file = path.join(tmpDir, `${name}.mjs`);
|
||||
writeFileSync(file, contents);
|
||||
entrypoints.push(file);
|
||||
}
|
||||
|
||||
await Bun.build({
|
||||
entrypoints,
|
||||
outdir: BUNEXT_VENDOR_DIR,
|
||||
splitting: true,
|
||||
format: "esm",
|
||||
target: "browser",
|
||||
minify: !dev,
|
||||
define: {
|
||||
"process.env.NODE_ENV": JSON.stringify(
|
||||
dev ? "development" : "production",
|
||||
),
|
||||
},
|
||||
});
|
||||
|
||||
rmSync(tmpDir, { force: true, recursive: true });
|
||||
|
||||
const PUBLIC_ROOT = BUNEXT_VENDOR_DIR.replace(BUNX_CWD_DIR, "/.bunext");
|
||||
|
||||
global.REACT_IMPORTS_MAP = {
|
||||
imports: {
|
||||
react: `${PUBLIC_ROOT}/react.js`,
|
||||
"react-dom": `${PUBLIC_ROOT}/react-dom.js`,
|
||||
"react-dom/client": `${PUBLIC_ROOT}/react-dom_client.js`,
|
||||
"react/jsx-runtime": `${PUBLIC_ROOT}/react_jsx-runtime.js`,
|
||||
"react/jsx-dev-runtime": `${PUBLIC_ROOT}/react_jsx-dev-runtime.js`,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -50,6 +50,8 @@ export default async function grabClientHydrationScript({
|
||||
let txt = ``;
|
||||
|
||||
txt += `import { hydrateRoot } from "${ROOT_DIR}/node_modules/react-dom/client.js";\n`;
|
||||
// txt += `import react from "${ROOT_DIR}/node_modules/react/index.js";\n`;
|
||||
|
||||
if (root_file_path) {
|
||||
txt += `import Root from "${root_file_path}";\n`;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
// plugins/react-vendor-chunk-plugin.ts
|
||||
import * as esbuild from "esbuild";
|
||||
import path from "path";
|
||||
import grabDirNames from "../../../utils/grab-dir-names";
|
||||
|
||||
const { BUNEXT_VENDOR_DIR } = grabDirNames();
|
||||
|
||||
const REACT_MODULES = new Set([
|
||||
"react",
|
||||
"react-dom",
|
||||
"react-dom/client",
|
||||
"react/jsx-runtime",
|
||||
"react/jsx-dev-runtime",
|
||||
]);
|
||||
|
||||
const VENDOR_BASE = "/.bunext/public/vendor";
|
||||
|
||||
const REACT_ENTRIES: Record<string, string> = {
|
||||
react: `
|
||||
import React from "react";
|
||||
export const {
|
||||
Children, Component, Fragment, Profiler, PureComponent, StrictMode,
|
||||
Suspense, cloneElement, createContext, createElement, createFactory,
|
||||
createRef, forwardRef, isValidElement, lazy, memo, startTransition,
|
||||
useCallback, useContext, useDebugValue, useDeferredValue, useEffect,
|
||||
useId, useImperativeHandle, useInsertionEffect, useLayoutEffect,
|
||||
useMemo, useReducer, useRef, useState, useSyncExternalStore,
|
||||
useTransition, version,
|
||||
} = React;
|
||||
export default React;
|
||||
`,
|
||||
"react-dom": `
|
||||
import ReactDOM from "react-dom";
|
||||
export const {
|
||||
createPortal, flushSync, findDOMNode, hydrate, render,
|
||||
unmountComponentAtNode, version,
|
||||
} = ReactDOM;
|
||||
export default ReactDOM;
|
||||
`,
|
||||
"react-dom/client": `
|
||||
import ReactDOMClient from "react-dom/client";
|
||||
export const { createRoot, hydrateRoot } = ReactDOMClient;
|
||||
export default ReactDOMClient;
|
||||
`,
|
||||
"react/jsx-runtime": `
|
||||
import JSXRuntime from "react/jsx-runtime";
|
||||
export const { jsx, jsxs, Fragment } = JSXRuntime;
|
||||
export default JSXRuntime;
|
||||
`,
|
||||
"react/jsx-dev-runtime": `
|
||||
import JSXDevRuntime from "react/jsx-dev-runtime";
|
||||
export const { jsxDEV, Fragment } = JSXDevRuntime;
|
||||
export default JSXDevRuntime;
|
||||
`,
|
||||
};
|
||||
|
||||
// Map bare specifier -> browser path
|
||||
function vendorPath(specifier: string): string {
|
||||
const filename = specifier.replace(/\//g, "_") + ".js";
|
||||
return `${VENDOR_BASE}/${filename}`;
|
||||
}
|
||||
|
||||
function vendorOutfile(specifier: string): string {
|
||||
const filename = specifier.replace(/\//g, "_") + ".js";
|
||||
return path.join(BUNEXT_VENDOR_DIR, filename);
|
||||
}
|
||||
|
||||
export default function reactVendorChunkPlugin(): esbuild.Plugin {
|
||||
let vendorReady: Promise<void>;
|
||||
|
||||
return {
|
||||
name: "react-vendor-chunk",
|
||||
setup(build) {
|
||||
vendorReady ??= buildAllVendorChunks(build.initialOptions);
|
||||
|
||||
build.onResolve(
|
||||
{ filter: /^react(-dom)?(\/.*)?$/ },
|
||||
async (args) => {
|
||||
const bare = args.path.replace(/\/index(\.m?js)?$/, "");
|
||||
if (!(bare in REACT_ENTRIES)) return;
|
||||
|
||||
await vendorReady;
|
||||
|
||||
return {
|
||||
path: vendorPath(bare),
|
||||
external: true,
|
||||
};
|
||||
},
|
||||
);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function buildAllVendorChunks(
|
||||
parentOptions: esbuild.BuildOptions,
|
||||
): Promise<void> {
|
||||
await Promise.all(
|
||||
Object.entries(REACT_ENTRIES).map(([specifier, contents]) =>
|
||||
esbuild.build({
|
||||
stdin: {
|
||||
contents,
|
||||
resolveDir: process.cwd(),
|
||||
loader: "tsx",
|
||||
},
|
||||
outfile: vendorOutfile(specifier),
|
||||
bundle: true,
|
||||
minify: parentOptions.minify,
|
||||
format: "esm",
|
||||
target: parentOptions.target as string,
|
||||
platform: "browser",
|
||||
define: parentOptions.define,
|
||||
mainFields: ["module", "main"],
|
||||
conditions: ["import", "default"],
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { Plugin } from "esbuild";
|
||||
import path from "path";
|
||||
import grabDirNames from "../../../utils/grab-dir-names";
|
||||
|
||||
const { ROOT_DIR } = grabDirNames();
|
||||
|
||||
const reactAliasPlugin: Plugin = {
|
||||
name: "react-alias",
|
||||
setup(build) {
|
||||
const reactPath = path.join(ROOT_DIR, "node_modules");
|
||||
|
||||
build.onResolve({ filter: /^react$/ }, () => ({
|
||||
path: path.join(reactPath, "react", "index.js"),
|
||||
}));
|
||||
|
||||
build.onResolve({ filter: /^react-dom$/ }, () => ({
|
||||
path: path.join(reactPath, "react-dom", "index.js"),
|
||||
}));
|
||||
|
||||
build.onResolve({ filter: /^react\/jsx-runtime$/ }, () => ({
|
||||
path: path.join(reactPath, "react", "jsx-runtime.js"),
|
||||
}));
|
||||
|
||||
build.onResolve({ filter: /^react\/jsx-dev-runtime$/ }, () => ({
|
||||
path: path.join(reactPath, "react", "jsx-dev-runtime.js"),
|
||||
}));
|
||||
},
|
||||
};
|
||||
|
||||
export default reactAliasPlugin;
|
||||
@@ -24,6 +24,22 @@ export default function virtualFilesPlugin({ entryToPage }: Params) {
|
||||
};
|
||||
});
|
||||
|
||||
build.onResolve(
|
||||
{ filter: /node_modules\/react(-dom)?/ },
|
||||
(args) => ({
|
||||
path: args.path.includes("react-dom")
|
||||
? args.path.includes("client")
|
||||
? "react-dom/client"
|
||||
: "react-dom"
|
||||
: args.path.includes("jsx-dev")
|
||||
? "react/jsx-dev-runtime"
|
||||
: args.path.includes("jsx")
|
||||
? "react/jsx-runtime"
|
||||
: "react",
|
||||
external: true,
|
||||
}),
|
||||
);
|
||||
|
||||
build.onLoad(
|
||||
{ filter: /.*/, namespace: "hydration-virtual" },
|
||||
(args) => {
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import * as esbuild from "esbuild";
|
||||
import grabDirNames from "../../utils/grab-dir-names";
|
||||
import isDevelopment from "../../utils/is-development";
|
||||
import path from "path";
|
||||
import { rmSync, mkdirSync, writeFileSync } from "fs";
|
||||
|
||||
const { BUNEXT_VENDOR_DIR, BUNX_CWD_DIR, ROOT_DIR } = grabDirNames();
|
||||
|
||||
const VENDOR_ENTRIES: Record<string, string> = {
|
||||
react: `
|
||||
import React from "react";
|
||||
export const {
|
||||
Children, Component, Fragment, Profiler, PureComponent, StrictMode,
|
||||
Suspense, cloneElement, createContext, createElement, createRef,
|
||||
forwardRef, isValidElement, lazy, memo, startTransition,
|
||||
useCallback, useContext, useDebugValue, useDeferredValue, useEffect,
|
||||
useId, useImperativeHandle, useInsertionEffect, useLayoutEffect,
|
||||
useMemo, useReducer, useRef, useState, useSyncExternalStore,
|
||||
useTransition, version, use, cache, act,
|
||||
} = React;
|
||||
export default React;
|
||||
`,
|
||||
"react-dom": `
|
||||
import ReactDOM from "react-dom";
|
||||
export const {
|
||||
createPortal, flushSync, version,
|
||||
} = ReactDOM;
|
||||
export default ReactDOM;
|
||||
`,
|
||||
"react-dom_client": `
|
||||
import ReactDOMClient from "react-dom/client";
|
||||
export const { createRoot, hydrateRoot } = ReactDOMClient;
|
||||
export default ReactDOMClient;
|
||||
`,
|
||||
"react_jsx-runtime": `
|
||||
import JSXRuntime from "react/jsx-runtime";
|
||||
export const { jsx, jsxs, Fragment } = JSXRuntime;
|
||||
`,
|
||||
"react_jsx-dev-runtime": `
|
||||
import JSXDevRuntime from "react/jsx-dev-runtime";
|
||||
export const { jsxDEV, Fragment } = JSXDevRuntime;
|
||||
`,
|
||||
};
|
||||
|
||||
export default async function reactModulesBundler() {
|
||||
const dev = isDevelopment();
|
||||
|
||||
rmSync(BUNEXT_VENDOR_DIR, { force: true, recursive: true });
|
||||
|
||||
const tmpDir = path.join(BUNEXT_VENDOR_DIR, "_tmp");
|
||||
mkdirSync(tmpDir, { recursive: true });
|
||||
|
||||
const entrypoints: Record<string, string> = {};
|
||||
for (const [name, contents] of Object.entries(VENDOR_ENTRIES)) {
|
||||
const file = path.join(tmpDir, `${name}.mjs`);
|
||||
writeFileSync(file, contents);
|
||||
entrypoints[name] = file;
|
||||
}
|
||||
|
||||
await esbuild.build({
|
||||
entryPoints: entrypoints,
|
||||
outdir: BUNEXT_VENDOR_DIR,
|
||||
bundle: true,
|
||||
splitting: true,
|
||||
format: "esm",
|
||||
platform: "browser",
|
||||
target: "es2020",
|
||||
minify: !dev,
|
||||
define: {
|
||||
"process.env.NODE_ENV": JSON.stringify(
|
||||
dev ? "development" : "production",
|
||||
),
|
||||
},
|
||||
});
|
||||
|
||||
rmSync(tmpDir, { force: true, recursive: true });
|
||||
|
||||
const PUBLIC_ROOT = BUNEXT_VENDOR_DIR.replace(BUNX_CWD_DIR, "/.bunext");
|
||||
|
||||
global.REACT_IMPORTS_MAP = {
|
||||
imports: {
|
||||
react: `${PUBLIC_ROOT}/react.js`,
|
||||
"react-dom": `${PUBLIC_ROOT}/react-dom.js`,
|
||||
"react-dom/client": `${PUBLIC_ROOT}/react-dom_client.js`,
|
||||
"react/jsx-runtime": `${PUBLIC_ROOT}/react_jsx-runtime.js`,
|
||||
"react/jsx-dev-runtime": `${PUBLIC_ROOT}/react_jsx-dev-runtime.js`,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import type { BuildContext } from "esbuild";
|
||||
import watcherEsbuildCTX from "./server/watcher-esbuild-ctx";
|
||||
import allPagesESBuildContextBundler from "./bundler/all-pages-esbuild-context-bundler";
|
||||
import serverPostBuildFn from "./server/server-post-build-fn";
|
||||
import reactModulesBundler from "./bundler/react-modules-bundler";
|
||||
|
||||
/**
|
||||
* # Declare Global Variables
|
||||
@@ -36,6 +37,8 @@ declare global {
|
||||
var SKIPPED_BROWSER_MODULES: Set<string>;
|
||||
var BUNDLER_CTX: BuildContext | undefined;
|
||||
var DIR_NAMES: ReturnType<typeof grabDirNames>;
|
||||
var REACT_IMPORTS_MAP: { imports: Record<string, string> };
|
||||
var REACT_DOM_SERVER: any;
|
||||
}
|
||||
|
||||
const dirNames = grabDirNames();
|
||||
@@ -48,8 +51,11 @@ export default async function bunextInit() {
|
||||
global.PAGE_FILES = [];
|
||||
global.SKIPPED_BROWSER_MODULES = new Set<string>();
|
||||
global.DIR_NAMES = dirNames;
|
||||
global.REACT_IMPORTS_MAP = { imports: {} };
|
||||
|
||||
await init();
|
||||
// await bunReactModulesBundler();
|
||||
await reactModulesBundler();
|
||||
log.banner();
|
||||
|
||||
const router = new Bun.FileSystemRouter({
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import grabDirNames from "../../utils/grab-dir-names";
|
||||
import path from "path";
|
||||
import isDevelopment from "../../utils/is-development";
|
||||
import { existsSync } from "fs";
|
||||
import { readFileResponse } from "./handle-public";
|
||||
|
||||
const { HYDRATION_DST_DIR } = grabDirNames();
|
||||
const { BUNEXT_PUBLIC_DIR } = grabDirNames();
|
||||
|
||||
type Params = {
|
||||
req: Request;
|
||||
@@ -15,54 +14,21 @@ export default async function ({ req }: Params): Promise<Response> {
|
||||
const is_dev = isDevelopment();
|
||||
const url = new URL(req.url);
|
||||
|
||||
// switch (url.pathname) {
|
||||
// case "/.bunext/react":
|
||||
// return readFileResponse({
|
||||
// file_path: is_dev
|
||||
// ? global.DIR_NAMES.REACT_DEVELOPMENT_MODULE
|
||||
// : global.DIR_NAMES.REACT_PRODUCTION_MODULE,
|
||||
// });
|
||||
// case "/.bunext/react-dom":
|
||||
// return readFileResponse({
|
||||
// file_path: is_dev
|
||||
// ? global.DIR_NAMES.REACT_DOM_DEVELOPMENT_MODULE
|
||||
// : global.DIR_NAMES.REACT_DOM_PRODUCTION_MODULE,
|
||||
// });
|
||||
// case "/.bunext/react-dom-client":
|
||||
// return readFileResponse({
|
||||
// file_path: is_dev
|
||||
// ? global.DIR_NAMES.REACT_DOM_CLIENT_DEVELOPMENT_MODULE
|
||||
// : global.DIR_NAMES.REACT_DOM_CLIENT_PRODUCTION_MODULE,
|
||||
// });
|
||||
// case "/.bunext/react-jsx-runtime":
|
||||
// return readFileResponse({
|
||||
// file_path: is_dev
|
||||
// ? global.DIR_NAMES.REACT_JSX_RUNTIME_DEVELOPMENT_MODULE
|
||||
// : global.DIR_NAMES.REACT_JSX_RUNTIME_PRODUCTION_MODULE,
|
||||
// });
|
||||
// case "/.bunext/react-jsx-dev-runtime":
|
||||
// return readFileResponse({
|
||||
// file_path: is_dev
|
||||
// ? global.DIR_NAMES
|
||||
// .REACT_JSX_DEVELOPMENT_RUNTIME_DEVELOPMENT_MODULE
|
||||
// : global.DIR_NAMES
|
||||
// .REACT_JSX_DEVELOPMENT_RUNTIME_PRODUCTION_MODULE,
|
||||
// });
|
||||
|
||||
// default:
|
||||
// break;
|
||||
// }
|
||||
|
||||
const file_path = path.join(
|
||||
HYDRATION_DST_DIR,
|
||||
url.pathname.replace(/\/\.bunext\/public\/pages\//, ""),
|
||||
BUNEXT_PUBLIC_DIR,
|
||||
url.pathname.replace(/\/\.bunext\/public\//, ""),
|
||||
);
|
||||
|
||||
if (!file_path.startsWith(HYDRATION_DST_DIR + path.sep)) {
|
||||
if (!file_path.startsWith(BUNEXT_PUBLIC_DIR + path.sep)) {
|
||||
return new Response("Forbidden", { status: 403 });
|
||||
}
|
||||
|
||||
return readFileResponse({ file_path });
|
||||
return readFileResponse({
|
||||
file_path,
|
||||
cache: url.pathname.includes("/vendor/")
|
||||
? { duration: 3600 }
|
||||
: undefined,
|
||||
});
|
||||
} catch (error) {
|
||||
return new Response(`File Not Found`, {
|
||||
status: 404,
|
||||
|
||||
@@ -31,7 +31,14 @@ export default async function ({ req }: Params): Promise<Response> {
|
||||
}
|
||||
}
|
||||
|
||||
export function readFileResponse({ file_path }: { file_path: string }) {
|
||||
type FileResponse = {
|
||||
file_path: string;
|
||||
cache?: {
|
||||
duration?: "infinite" | number;
|
||||
};
|
||||
};
|
||||
|
||||
export function readFileResponse({ file_path, cache }: FileResponse) {
|
||||
if (!existsSync(file_path)) {
|
||||
return new Response(`Public File Doesn't Exist`, {
|
||||
status: 404,
|
||||
@@ -40,7 +47,15 @@ export function readFileResponse({ file_path }: { file_path: string }) {
|
||||
|
||||
const file = Bun.file(file_path);
|
||||
|
||||
// let res_opts: ResponseInit = {};
|
||||
const headers = new Headers();
|
||||
|
||||
return new Response(file);
|
||||
if (cache?.duration == "infinite" || (cache && !cache.duration)) {
|
||||
headers.set("Cache-Control", "public, max-age=31536000, immutable");
|
||||
} else if (cache?.duration) {
|
||||
headers.set("Cache-Control", `public, max-age=${cache.duration}`);
|
||||
}
|
||||
|
||||
return new Response(file, {
|
||||
headers,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -6,23 +6,11 @@ import grabWebPageHydrationScript from "./grab-web-page-hydration-script";
|
||||
import grabWebMetaHTML from "./grab-web-meta-html";
|
||||
import { log } from "../../../utils/log";
|
||||
import { AppData } from "../../../data/app-data";
|
||||
import { readFileSync } from "fs";
|
||||
import path from "path";
|
||||
import _ from "lodash";
|
||||
import grabDirNames from "../../../utils/grab-dir-names";
|
||||
|
||||
const { ROOT_DIR } = grabDirNames();
|
||||
|
||||
let _reactVersion = "19";
|
||||
try {
|
||||
_reactVersion = JSON.parse(
|
||||
readFileSync(
|
||||
path.join(process.cwd(), "node_modules/react/package.json"),
|
||||
"utf-8",
|
||||
),
|
||||
).version;
|
||||
} catch {}
|
||||
|
||||
export default async function genWebHTML({
|
||||
component,
|
||||
pageProps,
|
||||
@@ -75,32 +63,6 @@ export default async function genWebHTML({
|
||||
const RootHead = root_module?.Head;
|
||||
|
||||
const dev = isDevelopment();
|
||||
const devSuffix = dev ? "?dev" : "";
|
||||
|
||||
// const browser_imports: Record<string, string> = {
|
||||
// react: `/.bunext/react`,
|
||||
// "react-dom": `/.bunext/react-dom`,
|
||||
// "react-dom/client": `/.bunext/react-dom-client`,
|
||||
// "react/jsx-runtime": `/.bunext/react-jsx-runtime`,
|
||||
// "react/jsx-dev-runtime": `/.bunext/react-jsx-dev-runtime`,
|
||||
// };
|
||||
|
||||
// const browser_imports: Record<string, string> = {
|
||||
// react: `https://esm.sh/react@${_reactVersion}`,
|
||||
// "react-dom": `https://esm.sh/react-dom@${_reactVersion}`,
|
||||
// "react-dom/client": `https://esm.sh/react-dom@${_reactVersion}/client`,
|
||||
// "react/jsx-runtime": `https://esm.sh/react@${_reactVersion}/jsx-runtime`,
|
||||
// "react/jsx-dev-runtime": `https://esm.sh/react@${_reactVersion}/jsx-dev-runtime`,
|
||||
// };
|
||||
|
||||
// if (dev) {
|
||||
// browser_imports["react/jsx-dev-runtime"] =
|
||||
// `https://esm.sh/react@${_reactVersion}/jsx-dev-runtime`;
|
||||
// }
|
||||
|
||||
// const importMap = JSON.stringify({
|
||||
// imports: browser_imports,
|
||||
// });
|
||||
|
||||
const final_meta = _.merge(root_meta, page_meta);
|
||||
|
||||
@@ -116,8 +78,6 @@ export default async function genWebHTML({
|
||||
|
||||
{final_meta ? grabWebMetaHTML({ meta: final_meta }) : null}
|
||||
|
||||
{/* <link rel="preconnect" href="https://esm.sh" /> */}
|
||||
|
||||
{bundledMap?.css_path ? (
|
||||
<link
|
||||
rel="stylesheet"
|
||||
@@ -140,14 +100,16 @@ export default async function genWebHTML({
|
||||
|
||||
{bundledMap?.path ? (
|
||||
<>
|
||||
{/* <script
|
||||
<script
|
||||
type="importmap"
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: importMap,
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: JSON.stringify(
|
||||
global.REACT_IMPORTS_MAP,
|
||||
),
|
||||
}}
|
||||
defer
|
||||
data-bunext-head
|
||||
/> */}
|
||||
/>
|
||||
<script
|
||||
src={`/${bundledMap.path}`}
|
||||
type="module"
|
||||
@@ -183,19 +145,14 @@ export default async function genWebHTML({
|
||||
|
||||
const stream = await renderToReadableStream(final_component, {
|
||||
onError(error: any) {
|
||||
// This is where you "omit" or handle the errors
|
||||
// You can log it silently or ignore it
|
||||
if (error.message.includes('unique "key" prop')) return;
|
||||
console.error(error);
|
||||
},
|
||||
});
|
||||
|
||||
// 2. Convert the Web Stream to a String (Bun-optimized)
|
||||
const htmlBody = await new Response(stream).text();
|
||||
|
||||
html += htmlBody;
|
||||
|
||||
// html += renderToString(final_component);
|
||||
|
||||
return html;
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ export default async function grabFilePathModule<T extends any = any>({
|
||||
format: "esm",
|
||||
target: "es2020",
|
||||
platform: "node",
|
||||
external: ["react", "react-dom"],
|
||||
// external: ["react", "react-dom"],
|
||||
minify: true,
|
||||
define: {
|
||||
"process.env.NODE_ENV": JSON.stringify(
|
||||
|
||||
@@ -94,6 +94,17 @@ export default async function (params?: Params) {
|
||||
script += ` oldCSSLink.remove();\n`;
|
||||
script += ` }\n`;
|
||||
|
||||
// script += ` const newScriptPath = \`/\${data.target_map.path}?t=\${Date.now()}\`;\n\n`;
|
||||
// script += ` try {\n`;
|
||||
// script += ` const mod = await import(newScriptPath);\n`;
|
||||
// script += ` if (typeof mod.default === "function" || typeof window.__BUNEXT_RERENDER__ === "function") {\n`;
|
||||
// script += ` window.__BUNEXT_RERENDER__?.();\n`;
|
||||
// script += ` }\n`;
|
||||
// script += ` } catch (importErr) {\n`;
|
||||
// script += ` console.error("HMR import failed, reloading:", importErr.message);\n`;
|
||||
// script += ` window.location.reload();\n`;
|
||||
// script += ` }\n`;
|
||||
|
||||
script += ` const newScriptPath = \`/\${data.target_map.path}?t=\${Date.now()}\`;\n\n`;
|
||||
script += ` const oldScript = document.getElementById("${AppData["BunextClientHydrationScriptID"]}");\n`;
|
||||
script += ` if (oldScript) {\n`;
|
||||
@@ -108,6 +119,7 @@ export default async function (params?: Params) {
|
||||
// script += ` }\n`;
|
||||
// script += ` console.log("newScript", newScript);\n`;
|
||||
script += ` document.head.appendChild(newScript);\n\n`;
|
||||
|
||||
script += ` } catch (err) {\n`;
|
||||
script += ` console.error("HMR update failed, falling back to reload:", err.message);\n`;
|
||||
script += ` window.location.reload();\n`;
|
||||
|
||||
@@ -23,6 +23,7 @@ export default function grabDirNames() {
|
||||
|
||||
const BUNEXT_PUBLIC_DIR = path.join(BUNX_CWD_DIR, "public");
|
||||
const HYDRATION_DST_DIR = path.join(BUNEXT_PUBLIC_DIR, "pages");
|
||||
const BUNEXT_VENDOR_DIR = path.join(BUNEXT_PUBLIC_DIR, "vendor");
|
||||
const BUNEXT_CACHE_DIR = path.join(BUNEXT_PUBLIC_DIR, "cache");
|
||||
const HYDRATION_DST_DIR_MAP_JSON_FILE_NAME = "map.json";
|
||||
const HYDRATION_DST_DIR_MAP_JSON_FILE = path.join(
|
||||
@@ -133,6 +134,8 @@ export default function grabDirNames() {
|
||||
BUNX_CWD_MODULE_CACHE_DIR,
|
||||
BUNX_CWD_PAGES_REWRITE_DIR,
|
||||
HYDRATION_DST_DIR_MAP_JSON_FILE_NAME,
|
||||
BUNEXT_VENDOR_DIR,
|
||||
BUNEXT_PUBLIC_DIR,
|
||||
// NODE_MODULES_DIR,
|
||||
// REACT_MODULE_DIR,
|
||||
// REACT_DOM_MODULE_DIR,
|
||||
|
||||
Reference in New Issue
Block a user