Skip to content

Commit d68cb99

Browse files
committed
inject chunk names into the html to save xhr rq
1 parent 74ce3d2 commit d68cb99

File tree

3 files changed

+31
-20
lines changed

3 files changed

+31
-20
lines changed

client/containers/App/index.js

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,9 @@ export default class App extends Component {
1212
}
1313

1414
componentDidMount() {
15-
fetch('/chunks.json')
16-
.then(res => res.json())
17-
.then(chunks => this.setState({
18-
preload: chunks.map(chunk => ({ href: chunk, rel: 'preload', as: 'script' }))
19-
}));
15+
this.setState({
16+
preload: window.__CHUNKS.map(chunk => ({ href: chunk, rel: 'preload', as: 'script' }))
17+
});
2018
}
2119

2220
render() {

client/index.ejs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,5 +7,6 @@
77
</head>
88
<body>
99
<div id="root"></div>
10+
<script>window.__CHUNKS=[];</script>
1011
</body>
1112
</html>

webpack.config.js

Lines changed: 27 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -43,22 +43,21 @@ const plugins = [
4343
function() {
4444
const compiler = this;
4545
const chunkRegEx = /^chunk[.]/;
46-
compiler.plugin('emit', function(compilation, callback) {
47-
const chunks = compilation
48-
.getStats()
49-
.toJson()
50-
.assets
51-
.filter(asset => chunkRegEx.test(asset.name))
52-
.map(asset => asset.name);
46+
compiler.plugin('compilation', function(compilation) {
47+
compilation.plugin('html-webpack-plugin-before-html-processing', function(htmlPluginData, cb) {
48+
// find all chunk file names
49+
const extractedChunks = compilation
50+
.chunks
51+
.reduce((chunks, chunk) => chunks.concat(chunk.files), [])
52+
.filter(chunk => chunkRegEx.test(chunk));
5353

54-
const json = JSON.stringify(chunks);
54+
// create a stringified version of the array
55+
const json = JSON.stringify(extractedChunks);
5556

56-
compilation.assets['chunks.json'] = {
57-
source: () => json,
58-
size: () => json.length
59-
};
60-
61-
callback();
57+
// inject chunks into the html
58+
htmlPluginData.html = htmlPluginData.html.replace('window.__CHUNKS=[];', `window.__CHUNKS=${json}`);
59+
cb(null, htmlPluginData);
60+
});
6261
});
6362
},
6463
];
@@ -165,6 +164,19 @@ module.exports = {
165164
inject: true,
166165
port: 3000,
167166
compress: isProd,
168-
stats: { colors: true },
167+
stats: {
168+
assets: true,
169+
children: false,
170+
chunks: false,
171+
hash: false,
172+
modules: false,
173+
publicPath: false,
174+
timings: true,
175+
version: false,
176+
warnings: true,
177+
colors: {
178+
green: '\u001b[32m',
179+
}
180+
},
169181
}
170182
};

0 commit comments

Comments
 (0)