-
Notifications
You must be signed in to change notification settings - Fork 627
/
ClientPlugin.js
57 lines (50 loc) · 1.92 KB
/
ClientPlugin.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
56
57
const fs = require('fs');
const path = require('path');
const webpack = require('webpack');
const getShellConfig = require('./ShellWebpackConfig.js');
const { createElement } = require('rax');
const renderer = require('rax-server-renderer');
const NAME = 'rax-client-webpack-plugin';
class ClientPlugin {
constructor(options) {
this.ready = false;
this.options = options;
this.AppShellTemplate = '';
}
apply(compiler) {
compiler.hooks.beforeCompile.tapAsync(NAME, (compilationParams, callback) => {
const pathConfig = this.options.pathConfig;
webpack(getShellConfig(pathConfig)).run((err) => {
if (err) {
console.error(err);
return false;
}
const shellJsPath = path.resolve(pathConfig.appBuild, './shells.js');
const component = require(shellJsPath).default;
this.AppShellTemplate = renderer.renderToString(createElement(component, {}, createElement('div', { id: 'root-page' })));
fs.unlinkSync(shellJsPath);
callback();
});
});
compiler.hooks.compilation.tap(NAME, bundle => {
bundle.hooks.optimizeModules.tap(NAME, modules => {
modules.forEach(mod => {
if (mod.resource && mod.resource.indexOf('public/index.html') > -1) {
mod._source._value = mod._source._value.replace(
'<div id="root"></div>',
`<div id="root">${this.AppShellTemplate}</div>`
);
// 如果开启 Service Worker
if (true) {
mod._source._value = mod._source._value.replace(
'</body>',
'<script>!function(){var e=document.createElement("script");e.src="/regSW.js?"+Date.now(),e.async=!0,e.type="text/javascript",e.crossOrigin="anonymous",document.head.insertBefore(e,document.head.firstChild)}();</script></body>'
);
}
}
});
});
});
}
}
module.exports = ClientPlugin;