11import { createServer } from 'http' ;
2- import * as React from 'react' ;
3- import { renderToString } from 'react-dom/server' ;
2+ import { createFactory } from 'react' ;
3+ import { renderToNodeStream } from 'react-dom/server' ;
44import { readFile } from 'fs' ;
55import { promisify } from 'util' ;
66import AppComponent from './components/app' ;
@@ -10,7 +10,7 @@ import { faviconUrl, stylesUrl, reactUrl, reactDomUrl, browserUrl, browserMapUrl
1010console . log ( 'Server booting...' ) ;
1111const isProd = process . env . NODE_ENV === 'production' ;
1212console . log ( 'Production optimization enabled? ' , isProd ) ;
13- const App = React . createFactory ( AppComponent ) ;
13+ const App = createFactory ( AppComponent ) ;
1414const PORT = process . env . PORT || 3007 ;
1515const suffix = isProd ? '.production.min.js' : '.development.js' ;
1616const readFileAsync = promisify ( readFile ) ;
@@ -19,26 +19,30 @@ createServer(async (req, res) => {
1919 const { httpVersion, method, url } = req ;
2020 console . log ( `${ httpVersion } ${ method } ${ url } ` ) ;
2121 if ( url === '/' ) {
22- const props : AppProps = { items : getItems ( ) } ;
23- const reactHtml = renderToString ( App ( props ) ) ;
24- const pageHtml = `<!DOCTYPE html>
25- <html>
26- <head>
27- <meta charset="utf-8" />
28- <meta name="viewport" content="width=device-width, initial-scale=1.0">
29- <link href="${ faviconUrl } " rel="icon" type="image/x-icon" />
30- <title>React Example</title>
31- <link rel="stylesheet" href="${ stylesUrl } " />
32- </head>
33- <body>
34- <div id="${ containerId } ">${ reactHtml } </div>
35- <script src="${ reactUrl } "></script>
36- <script src="${ reactDomUrl } "></script>
37- <script src="${ browserUrl } "></script>
38- </body>
39- </html>` ;
22+
4023 res . setHeader ( 'Content-Type' , 'text/html' ) ;
41- res . end ( pageHtml )
24+ res . write ( '<!DOCTYPE html>' ) ;
25+ res . write ( `<html>
26+ <head>
27+ <meta charset="utf-8" />
28+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
29+ <link href="${ faviconUrl } " rel="icon" type="image/x-icon" />
30+ <title>React Example</title>
31+ <link rel="stylesheet" href="${ stylesUrl } " />
32+ </head>
33+ <body>
34+ <div id="${ containerId } ">` ) ;
35+ const props : AppProps = { items : getItems ( ) } ;
36+ const stream = renderToNodeStream ( App ( props ) ) as any ;
37+ stream . pipe ( res , { end : false } ) ;
38+ stream . on ( 'end' , ( ) => {
39+ res . end ( `</div>
40+ <script src="${ reactUrl } "></script>
41+ <script src="${ reactDomUrl } "></script>
42+ <script src="${ browserUrl } "></script>
43+ </body>
44+ </html>` ) ;
45+ } ) ;
4246 } else if ( url === propsUrl ) {
4347 const items = getItems ( ) ;
4448 const props = { items : items } ;
0 commit comments