@@ -12,6 +12,18 @@ const createBundleRenderer = require('vue-server-renderer').createBundleRenderer
12
12
13
13
const app = express ( )
14
14
15
+ // parse index.html template
16
+ const html = ( ( ) => {
17
+ const template = fs . readFileSync ( resolve ( './index.html' ) , 'utf-8' )
18
+ const i = template . indexOf ( '{{ APP }}' )
19
+ // styles are injected dynamically via vue-style-loader in development
20
+ const style = isProd ? '<link rel="stylesheet" href="/dist/styles.css">' : ''
21
+ return {
22
+ head : template . slice ( 0 , i ) . replace ( '{{ STYLE }}' , style ) ,
23
+ tail : template . slice ( i + '{{ APP }}' . length )
24
+ }
25
+ } ) ( )
26
+
15
27
let renderer
16
28
if ( isProd ) {
17
29
// create server renderer from real fs
@@ -36,42 +48,34 @@ app.use('/dist', express.static(resolve('./dist')))
36
48
app . use ( favicon ( path . resolve ( __dirname , 'src/assets/logo.png' ) ) )
37
49
38
50
app . get ( '*' , ( req , res ) => {
51
+ if ( ! renderer ) {
52
+ return res . end ( 'waiting for compilation... refresh in a moment.' )
53
+ }
54
+
39
55
var s = Date . now ( )
40
56
const context = { url : req . url }
41
57
const renderStream = renderer . renderToStream ( context )
42
58
let firstChunk = true
43
59
44
- res . write ( `<!DOCTYPE html>
45
- <html lang="en">
46
- <head>
47
- <meta charset="utf-8">
48
- <title>vue-ssr-starter-kit</title>
49
- <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">
50
- ${ process . env . NODE_ENV === 'production'
51
- ? `<link rel="stylesheet" href="/dist/styles.css">`
52
- : `` }
53
- </head>
54
- <body>` )
60
+ res . write ( html . head )
55
61
56
62
renderStream . on ( 'data' , chunk => {
57
63
if ( firstChunk ) {
58
- // send down initial store state
64
+ // embed initial store state
59
65
if ( context . initialState ) {
60
- res . write ( `<script>window.__INITIAL_STATE__=${
61
- serialize ( context . initialState , { isJSON : true } )
62
- } </script>`)
66
+ res . write (
67
+ `<script>window.__INITIAL_STATE__=${
68
+ serialize ( context . initialState , { isJSON : true } )
69
+ } </script>`
70
+ )
63
71
}
64
72
firstChunk = false
65
73
}
66
74
res . write ( chunk )
67
75
} )
68
76
69
77
renderStream . on ( 'end' , ( ) => {
70
- res . end ( `
71
- <script src="/dist/client-vendor-bundle.js"></script>
72
- <script src="/dist/client-bundle.js"></script>
73
- </body></html>`
74
- )
78
+ res . end ( html . tail )
75
79
console . log ( `whole request: ${ Date . now ( ) - s } ms` )
76
80
} )
77
81
0 commit comments