1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | import path from 'path';
|
18 | import loaderUtils from 'loader-utils';
|
19 | import slash from 'slash';
|
20 |
|
21 | const comlinkLoaderSpecificOptions = [
|
22 | 'multiple', 'multi',
|
23 | 'singleton'
|
24 | ];
|
25 |
|
26 | export default function loader () { }
|
27 |
|
28 | loader.pitch = function (request) {
|
29 | const options = loaderUtils.getOptions(this) || {};
|
30 | const singleton = options.singleton;
|
31 | const workerLoaderOptions = {};
|
32 | for (let i in options) {
|
33 | if (comlinkLoaderSpecificOptions.indexOf(i) === -1) {
|
34 | workerLoaderOptions[i] = options[i];
|
35 | }
|
36 | }
|
37 |
|
38 | const workerLoader = `!worker-loader?${JSON.stringify(workerLoaderOptions)}!${slash(path.resolve(__dirname, 'comlink-worker-loader.js'))}`;
|
39 |
|
40 | const remainingRequest = JSON.stringify(workerLoader + '!' + request);
|
41 |
|
42 |
|
43 | if (singleton === true) {
|
44 | return `
|
45 | module.exports = require('comlink').wrap(require(${remainingRequest})());
|
46 | ${options.module === false ? '' : 'module.exports.__esModule = true;'}
|
47 | `.replace(/\n\s*/g, '');
|
48 | }
|
49 |
|
50 |
|
51 | if (singleton === false) {
|
52 | return `
|
53 | module.exports = function () {
|
54 | return require('comlink').wrap(require(${remainingRequest})());
|
55 | };
|
56 | `.replace(/\n\s*/g, '');
|
57 | }
|
58 |
|
59 | return `
|
60 | var wrap = require('comlink').wrap,
|
61 | Worker = require(${remainingRequest}),
|
62 | inst;
|
63 | module.exports = function f() {
|
64 | if (this instanceof f) return wrap(Worker());
|
65 | return inst || (inst = wrap(Worker()));
|
66 | };
|
67 | `.replace(/\n\s*/g, '');
|
68 | };
|