UNPKG

2.19 kBJavaScriptView Raw
1/**
2 * Copyright 2018 Google LLC
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 * use this file except in compliance with the License. You may obtain a copy of
6 * the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 * License for the specific language governing permissions and limitations under
14 * the License.
15 */
16
17import path from 'path';
18import loaderUtils from 'loader-utils';
19import slash from 'slash';
20
21const comlinkLoaderSpecificOptions = [
22 'multiple', 'multi', // @todo: remove these
23 'singleton'
24];
25
26export default function loader () { }
27
28loader.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 // ?singleton mode: export an instance of the worker
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 // ?singleton=false mode: always return a new worker from the factory
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};