This repository has been archived by the owner on Jan 7, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEvaluateBundlePlugin.js
80 lines (66 loc) · 2.17 KB
/
EvaluateBundlePlugin.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
69
70
71
72
73
74
75
76
77
78
79
80
const vm = require('vm');
const path = require('path');
const invariant = require('invariant');
function EvaluateBundlePlugin({ callback }) {
this.renderCallback = callback;
}
EvaluateBundlePlugin.prototype.apply = function(compiler) {
if (!this.renderCallback) {
return;
}
compiler.plugin('emit', (compilation, compileCallback) => {
let entryBundleName;
// TODO: make sure this works with bundle splitting (it probably doesn't)
for (const chunk of compilation.chunks) {
if (chunk.hasRuntime()) {
entryBundleName = chunk.files[0];
break;
}
}
const statsObj = compilation.getStats().toJson();
const sourceAsset = compilation.assets[entryBundleName];
const source = sourceAsset.source();
const script = new vm.Script(source, {
filename: path.join(compiler.outputPath, entryBundleName),
});
const context = vm.createContext({ console });
console.log(
'\n\nHERE U GO: %s\n\n',
path.join(compiler.outputPath, entryBundleName)
);
let bundleExport;
try {
bundleExport = script.runInContext(context);
} catch (e) {
compilation.errors.push('EvaluateBundlePlugin: ' + e.stack);
}
const extraChunks = this.renderCallback(bundleExport, statsObj);
// TODO: consider using module module
// const Module = require('module');
// const filePath = path.join(compiler.outputPath, entryBundleName);
// const bundle = new Module();
// bundle.paths = module.paths;
// try {
// bundle._compile(source, filePath);
// } catch (e) {
// compilation.errors.push('EvaluateBundlePlugin: ' + e.stack);
// }
// const extraChunks = this.renderCallback(bundle.exports, statsObj);
invariant(
typeof extraChunks === 'object' && extraChunks !== null,
'EvaluateBundlePlugin callback must return an object'
);
for (const assetPath of Object.keys(extraChunks)) {
compilation.assets[assetPath] = {
source() {
return extraChunks[assetPath];
},
size() {
return extraChunks[assetPath].length;
},
};
}
compileCallback();
});
};
module.exports = EvaluateBundlePlugin;