8
8
copyFileSync ,
9
9
} from "fs" ;
10
10
import { dirname , join } from "path" ;
11
+ import { Writable } from "stream" ;
11
12
import * as ReactDOMServer from "react-dom/server" ;
12
13
import yargs from "yargs" ;
13
14
import { hideBin } from "yargs/helpers" ;
@@ -44,6 +45,25 @@ async function copyDirSync(src: string, dest: string) {
44
45
}
45
46
}
46
47
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
+
47
67
// Update your prerender and path discovery logic accordingly
48
68
async function prerender ( { api } : { api : string } ) {
49
69
process . chdir ( __dirname ) ;
@@ -64,8 +84,8 @@ async function prerender({ api }: { api: string }) {
64
84
return json ;
65
85
}
66
86
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 ) ) ;
69
89
return htmlTemplate
70
90
. replace ( '"$bootstrap"' , JSON . stringify ( bootstrap ) )
71
91
. replace ( "$content" , content )
@@ -94,12 +114,12 @@ async function prerender({ api }: { api: string }) {
94
114
const route = routes [ i ] ;
95
115
console . log ( `Rendering ${ route } ` ) ;
96
116
const bootstrap = readAndExtractStaticAPI ( [ "api" ] ) ;
97
- write ( route , render ( bootstrap ) ) ;
117
+ write ( route , await render ( bootstrap ) ) ;
98
118
}
99
119
100
120
console . log ( `Rendering 404 page` ) ;
101
121
const bootstrap = { content : "not found 🔍" } ;
102
- write ( "/" , render ( bootstrap ) , "404.html" ) ;
122
+ write ( "/" , await render ( bootstrap ) , "404.html" ) ;
103
123
104
124
const timeTaken = new Date ( ) . getTime ( ) - startTime ;
105
125
console . log ( "--------------------------------" ) ;
0 commit comments