UNPKG

2.32 kBJavaScriptView Raw
1const ejs = require('ejs')
2
3const readClientFile = require('../utils/read-client-file')
4const getClientFilePath = require('../utils/get-client-file-path')
5
6/**
7 * 渲染 ejs 模板
8 * @param {Object} options
9 * @param {String} options.template ejs 模板内容
10 * @param {Object} [options.inject={}] 注入对象
11 * @param {Object} [options.state] 当前 Redux state。也可以传入 Redux store
12 * @param {Object} [options.compilation] webpack compilation
13 * @returns {String}
14 */
15module.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 // 开发模式: 将 content('critical.js') 转为 pathname() 方式
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
57const 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`