Skip to content

Commit 0863373

Browse files
committed
use React 18 renderToPipeableStream during prerender
1 parent 0dcb377 commit 0863373

File tree

1 file changed

+24
-4
lines changed

1 file changed

+24
-4
lines changed

src/prerender.ts

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
copyFileSync,
99
} from "fs";
1010
import { dirname, join } from "path";
11+
import { Writable } from "stream";
1112
import * as ReactDOMServer from "react-dom/server";
1213
import yargs from "yargs";
1314
import { hideBin } from "yargs/helpers";
@@ -44,6 +45,25 @@ async function copyDirSync(src: string, dest: string) {
4445
}
4546
}
4647

48+
async function renderToString(content: React.ReactNode) {
49+
const { pipe } = ReactDOMServer.renderToPipeableStream(content);
50+
return new Promise<string>((res) => {
51+
const chunks: Buffer[] = [];
52+
pipe(
53+
new Writable({
54+
write(chunk, encoding, callback) {
55+
chunks.push(chunk);
56+
callback();
57+
},
58+
final(callback) {
59+
res(Buffer.concat(chunks).toString());
60+
callback();
61+
},
62+
})
63+
);
64+
});
65+
}
66+
4767
// Update your prerender and path discovery logic accordingly
4868
async function prerender({ api }: { api: string }) {
4969
process.chdir(__dirname);
@@ -64,8 +84,8 @@ async function prerender({ api }: { api: string }) {
6484
return json;
6585
}
6686

67-
function render(bootstrap: { content: string }) {
68-
const content = ReactDOMServer.renderToString(createApp(bootstrap));
87+
async function render(bootstrap: { content: string }) {
88+
const content = await renderToString(createApp(bootstrap));
6989
return htmlTemplate
7090
.replace('"$bootstrap"', JSON.stringify(bootstrap))
7191
.replace("$content", content)
@@ -94,12 +114,12 @@ async function prerender({ api }: { api: string }) {
94114
const route = routes[i];
95115
console.log(`Rendering ${route}`);
96116
const bootstrap = readAndExtractStaticAPI(["api"]);
97-
write(route, render(bootstrap));
117+
write(route, await render(bootstrap));
98118
}
99119

100120
console.log(`Rendering 404 page`);
101121
const bootstrap = { content: "not found 🔍" };
102-
write("/", render(bootstrap), "404.html");
122+
write("/", await render(bootstrap), "404.html");
103123

104124
const timeTaken = new Date().getTime() - startTime;
105125
console.log("--------------------------------");

0 commit comments

Comments
 (0)