diff --git a/README.md b/README.md index 72c4e736..6d4b5412 100644 --- a/README.md +++ b/README.md @@ -176,6 +176,13 @@ module.exports = { }; ``` +### workerType + +Type: `string` +Default: `Worker` + +Set the worker type. Defaults to `Worker`. Supports `ServiceWorker`, `SharedWorker`. + ## Examples ### Basic diff --git a/src/options.json b/src/options.json index 27e5ea42..50d1a70e 100644 --- a/src/options.json +++ b/src/options.json @@ -12,6 +12,9 @@ }, "publicPath": { "type": "string" + }, + "workerType": { + "type": "string" } }, "additionalProperties": false diff --git a/src/workers/InlineWorker.js b/src/workers/InlineWorker.js index ada87c34..e5130fc0 100644 --- a/src/workers/InlineWorker.js +++ b/src/workers/InlineWorker.js @@ -5,7 +5,18 @@ var URL = window.URL || window.webkitURL; -module.exports = function inlineWorker(content, url) { +function CreateWorker(url, workerType) { + switch (workerType) { + case 'SharedWorker': + return new SharedWorker(url); + case 'ServiceWorker': + return new ServiceWorker(url); + default: + return new Worker(url); + } +} + +module.exports = function inlineWorker(content, url, workerType) { try { try { var blob; @@ -28,10 +39,11 @@ module.exports = function inlineWorker(content, url) { blob = new Blob([content]); } - return new Worker(URL.createObjectURL(blob)); + return CreateWorker(URL.createObjectURL(blob), workerType); } catch (e) { - return new Worker( - 'data:application/javascript,' + encodeURIComponent(content) + return CreateWorker( + 'data:application/javascript,' + encodeURIComponent(content), + workerType ); } } catch (e) { @@ -39,6 +51,6 @@ module.exports = function inlineWorker(content, url) { throw Error('Inline worker is not supported'); } - return new Worker(url); + return CreateWorker(url, workerType); } }; diff --git a/src/workers/index.js b/src/workers/index.js index af881eeb..c64b9e48 100644 --- a/src/workers/index.js +++ b/src/workers/index.js @@ -17,10 +17,22 @@ const getWorker = (file, content, options) => { return `require(${InlineWorkerPath})(${JSON.stringify( content - )}, ${fallbackWorkerPath})`; + )}, ${fallbackWorkerPath}, ${options.workerType})`; } - return `new Worker(${publicWorkerPath})`; + let worker = 'Worker'; + switch (options.workerType) { + case 'SharedWorker': + worker = 'SharedWorker'; + break; + case 'ServiceWorker': + worker = 'ServiceWorker'; + break; + default: + worker = 'Worker'; + } + + return `new ${worker}(${publicWorkerPath})`; }; export default getWorker;