This repository has been archived by the owner on Aug 20, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
69 lines (56 loc) · 2.4 KB
/
index.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
// Heavily based on https://github.com/webpack/worker-loader/blob/master/index.js
const path = require("path"),
WebWorkerTemplatePlugin = require("webpack/lib/webworker/WebWorkerTemplatePlugin"),
SingleEntryPlugin = require("webpack/lib/SingleEntryPlugin"),
loaderUtils = require("loader-utils");
module.exports = function() {};
module.exports.pitch = function(request) {
if(!this.webpack) throw new Error("Only usable with webpack");
this.cacheable(false);
const callback = this.async(),
query = loaderUtils.parseQuery(this.query),
filename = loaderUtils.interpolateName(this, query.name || "[hash].worker.js", {
context: query.context || this.options.context,
regExp: query.regExp
}),
outputOptions = {
filename: filename,
chunkFilename: "[id]." + filename,
namedChunkFilename: null
};
if(this.options && this.options.worker && this.options.worker.output) {
for(var name in this.options.worker.output) {
outputOptions[name] = this.options.worker.output[name];
}
}
const workerCompiler = this._compilation.createChildCompiler("worker", outputOptions);
workerCompiler.apply(new WebWorkerTemplatePlugin(outputOptions));
workerCompiler.apply(new SingleEntryPlugin(this.context, "!!" + request, "main"));
if(this.options && this.options.worker && this.options.worker.plugins) {
this.options.worker.plugins.forEach(function(plugin) {
workerCompiler.apply(plugin);
});
}
const subCache = `subcache ${__dirname} request`;
workerCompiler.plugin("compilation", function(compilation) {
if(compilation.cache) {
if(!compilation.cache[subCache])
compilation.cache[subCache] = {};
compilation.cache = compilation.cache[subCache];
}
});
workerCompiler.runAsChild(function(err, entries, compilation) {
if(err) return callback(err);
if (entries[0]) {
const factoryCode = getFactoryCode(entries[0].files[0]);
return callback(null, `module.exports = ${factoryCode};`);
} else {
return callback(null, null);
}
});
};
function getFactoryCode(workerFile) {
return `function(bootstrapRender, providers) {
return bootstrapRender(__webpack_public_path__ + ${JSON.stringify(workerFile)}, providers);
}\n`
}