-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathplugin.js
55 lines (44 loc) · 1.35 KB
/
plugin.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/* eslint no-eval: "off" */
const React = require('react')
const ReactDOMServer = require('react-dom/server')
class ReactCompilerPlugin {
constructor (options) {
this.options = options
}
apply (compiler) {
compiler.plugin('emit', (compilation, done) => {
const assets = compilation.assets
try {
const source = assets['bundle.js'].source()
const pages = eval(source)
for (let route in pages) {
if (pages.hasOwnProperty(route)) {
const Page = pages[route]
const layoutProps = Page.layoutProps || {}
const Layout = layoutProps.layout
let page = React.createElement(Page)
let doctype = '<!doctype html>'
if (Layout) {
page = React.createElement(Layout, Page.layoutProps, page)
if (Layout.doctype) {
doctype = Layout.doctype
}
}
const content = doctype + ReactDOMServer.renderToString(page)
if (route === 'default') {
route = 'index'
}
compilation.assets[`${route}.html`] = {
source: () => content,
size: () => content.length
}
}
}
} catch (err) {
console.error(err)
}
done()
})
}
}
module.exports = ReactCompilerPlugin