-
Notifications
You must be signed in to change notification settings - Fork 15
/
ChunkBundlerPlugin.js
68 lines (61 loc) · 2.63 KB
/
ChunkBundlerPlugin.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
58
59
60
61
62
63
64
65
66
67
68
const _ = require('lodash');
class ChunkBundlerPlugin {
constructor(options) {
this.options = options || {}
}
apply(compiler) {
compiler.plugin('emit', (compilation, compileCallback) => {
const resolvedPaths = {};
const promises = [];
_.each(this.options, (modules, url) => {
resolvedPaths[url] = [];
const resolvedChunkPaths = modules.map(module => {
return new Promise(resolve => {
compiler.resolvers.normal.resolve(compiler.options.context, '', module, (err, res) => {
resolvedPaths[url].push(res);
resolve();
});
});
});
promises.push(Promise.all(resolvedChunkPaths));
});
const mappedChunks = {};
Promise.all(promises).then(() => {
// Try finding the resolved chunk paths in the chunks modules
_.each(resolvedPaths, (paths, url) => {
mappedChunks[url] = [];
compilation.chunks.map(chunk => {
chunk.mapModules(module => {
if (module.resource && paths.includes(module.resource)) {
mappedChunks[url].push(
(process.env.NODE_ENV !== 'production' ? '// ' + chunk.files[0] + "\n\n" : '') + compilation.assets[chunk.files[0]].source()
);
}
});
});
});
let index = 0;
// Write new meta
let meta = JSON.parse(compilation.assets['meta.json'].source());
_.each(mappedChunks, (source, url) => {
const src = source.join('');
const bundleFile = 'bundles/bundle-' + index + '.js';
compilation.assets[bundleFile] = {
source: () => src,
size: () => src.length
};
_.set(meta, 'bundles.' + url, compiler.options.output.publicPath + bundleFile);
index++;
});
// Assign new meta.json to output assets
meta = JSON.stringify(meta, null, 4);
compilation.assets['meta.json'] = {
source: () => meta,
size: () => meta.length
};
compileCallback();
});
});
}
}
module.exports = ChunkBundlerPlugin;