1 | const ejs = require('ejs')
|
2 |
|
3 | const readClientFile = require('../utils/read-client-file')
|
4 | const getClientFilePath = require('../utils/get-client-file-path')
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 | module.exports = ({
|
16 | template = DEFAULT_TEMPLATE,
|
17 | inject = {},
|
18 | store, state,
|
19 | compilation,
|
20 | }) => {
|
21 |
|
22 | if (typeof state !== 'object' && typeof store === 'object' && typeof store.getState === 'function')
|
23 | state = store.getState()
|
24 | else if (typeof state === 'object' && typeof state.getState === 'function')
|
25 | state = state.getState()
|
26 |
|
27 | try {
|
28 | for (let key in inject) {
|
29 | if (typeof inject[key] === 'function')
|
30 | inject[key] = inject[key](template, state)
|
31 | }
|
32 | } catch (e) {
|
33 | console.log(e)
|
34 | }
|
35 |
|
36 |
|
37 | if (process.env.WEBPACK_BUILD_ENV === 'dev')
|
38 | template = template
|
39 | .replace(
|
40 | /<script(.*?)><%(.*?)content\(['"]critical\.js['"]\)(.*?)%><\/script>/,
|
41 | `<script$1 src="<%$2pathname('critical.js')$3%>"></script>`
|
42 | )
|
43 |
|
44 | // console.log(template)
|
45 |
|
46 | const localeId = typeof state === 'object' ? state.localeId : undefined
|
47 |
|
48 | return ejs.render(
|
49 | template, {
|
50 | inject,
|
51 | content: (filename) => readClientFile(filename, localeId, compilation),
|
52 | pathname: (filename) => getClientFilePath(filename, localeId),
|
53 | }, {}
|
54 | )
|
55 | }
|
56 |
|
57 | const DEFAULT_TEMPLATE = `
|
58 | <!DOCTYPE html>
|
59 | <html lang="en">
|
60 | <head>
|
61 | <meta charset="UTF-8">
|
62 | <script>//inject_meta</script>
|
63 | <title><script>//inject_title</script></title>
|
64 | <script>//inject_component_styles</script>
|
65 | </head>
|
66 | <body>
|
67 | <div id="root">
|
68 | <div><script>//inject_html</script></div>
|
69 | </div>
|
70 | <script>//inject_redux_state</script>
|
71 | <script>//inject_js</script>
|
72 | </body>
|
73 | </html>
|
74 | `
|