improve module support for WebWorkers

This commit is contained in:
Tobias Koppers 2021-06-28 12:30:25 +02:00
parent 31bb311f11
commit 0a64c16a89
15 changed files with 1173 additions and 34 deletions

View File

@ -141,7 +141,7 @@ export function reset() {
/******/ };
/******/
/******/ __webpack_require__.f.j = (chunkId, promises) => {
/******/ // JSONP chunk loading for javascript
/******/ // import() chunk loading for javascript
/******/ var installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;
/******/ if(installedChunkData !== 0) { // 0 means "already installed".
/******/
@ -232,9 +232,9 @@ var e,o={},t={};function r(e){var n=t[e];if(void 0!==n)return n.exports;var i=t[
```
asset output.js 6.35 KiB [emitted] [javascript module] (name: main)
asset 1.output.js 1.36 KiB [emitted] [javascript module]
chunk (runtime: main) output.js (main) 420 bytes (javascript) 2.89 KiB (runtime) [entry] [rendered]
chunk (runtime: main) output.js (main) 420 bytes (javascript) 2.9 KiB (runtime) [entry] [rendered]
> ./example.js main
runtime modules 2.89 KiB 6 modules
runtime modules 2.9 KiB 6 modules
./example.js + 1 modules 420 bytes [built] [code generated]
[no exports]
[no exports used]
@ -255,9 +255,9 @@ webpack 5.40.0 compiled successfully
```
asset output.js 1.15 KiB [emitted] [javascript module] [minimized] (name: main)
asset 946.output.js 213 bytes [emitted] [javascript module] [minimized]
chunk (runtime: main) output.js (main) 420 bytes (javascript) 2.89 KiB (runtime) [entry] [rendered]
chunk (runtime: main) output.js (main) 420 bytes (javascript) 2.9 KiB (runtime) [entry] [rendered]
> ./example.js main
runtime modules 2.89 KiB 6 modules
runtime modules 2.9 KiB 6 modules
./example.js + 1 modules 420 bytes [built] [code generated]
[no exports]
[no exports used]

View File

@ -0,0 +1,886 @@
# example.js
```javascript
document.body.innerHTML = `
<pre id="history"></pre>
<form>
<input id="message" type="text">
<button id="send">Send Message</button>
</form>
<p>Computing fibonacci without worker:</p>
<input id="fib1" type="number">
<pre id="output1"></pre>
<p>Computing fibonacci with worker:</p>
<input id="fib2" type="number">
<pre id="output2"></pre>
`;
const history = document.getElementById("history");
const message = document.getElementById("message");
const send = document.getElementById("send");
const fib1 = document.getElementById("fib1");
const output1 = document.getElementById("output1");
const fib2 = document.getElementById("fib2");
const output2 = document.getElementById("output2");
/// CHAT with shared worker ///
const chatWorker = new SharedWorker(
new URL("./chat-worker.js", import.meta.url),
{
name: "chat",
type: "module"
}
);
let historyTimeout;
const scheduleUpdateHistory = () => {
clearTimeout(historyTimeout);
historyTimeout = setTimeout(() => {
chatWorker.port.postMessage({ type: "history" });
}, 1000);
};
scheduleUpdateHistory();
const from = `User ${Math.floor(Math.random() * 10000)}`;
send.addEventListener("click", e => {
chatWorker.port.postMessage({
type: "message",
content: message.value,
from
});
message.value = "";
message.focus();
e.preventDefault();
});
chatWorker.port.onmessage = event => {
const msg = event.data;
switch (msg.type) {
case "history":
history.innerText = msg.history.join("\n");
scheduleUpdateHistory();
break;
}
};
/// FIBONACCI without worker ///
fib1.addEventListener("change", async () => {
try {
const value = parseInt(fib1.value, 10);
const { fibonacci } = await import("./fibonacci");
const result = fibonacci(value);
output1.innerText = `fib(${value}) = ${result}`;
} catch (e) {
output1.innerText = e.message;
}
});
/// FIBONACCI with worker ///
const fibWorker = new Worker(new URL("./fib-worker.js", import.meta.url), {
name: "fibonacci",
type: "module"
/* webpackEntryOptions: { filename: "workers/[name].js" } */
});
fib2.addEventListener("change", () => {
try {
const value = parseInt(fib2.value, 10);
fibWorker.postMessage(`${value}`);
} catch (e) {
output2.innerText = e.message;
}
});
fibWorker.onmessage = event => {
output2.innerText = event.data;
};
```
# fib-worker.js
```javascript
onmessage = async event => {
const { fibonacci } = await import("./fibonacci");
const value = JSON.parse(event.data);
postMessage(`fib(${value}) = ${fibonacci(value)}`);
};
```
# fibonacci.js
```javascript
export function fibonacci(n) {
return n < 1 ? 0 : n <= 2 ? 1 : fibonacci(n - 1) + fibonacci(n - 2);
}
```
# chat-worker.js
```javascript
onconnect = function (e) {
for (const port of e.ports) {
port.onmessage = async event => {
const msg = event.data;
switch (msg.type) {
case "message":
const { add } = await import("./chat-module");
add(msg.content, msg.from);
// fallthrough
case "history":
const { history } = await import("./chat-module");
port.postMessage({
type: "history",
history
});
break;
}
};
}
};
```
# chat-module.js
```javascript
export const history = [];
export const add = (content, from) => {
if (history.length > 10) history.shift();
history.push(`${from}: ${content}`);
};
```
# dist/main.js
```javascript
/******/ var __webpack_modules__ = ({});
```
<details><summary><code>/* webpack runtime code */</code></summary>
``` js
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ // no module.id needed
/******/ // no module.loaded needed
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = __webpack_modules__;
/******/
/************************************************************************/
/******/ /* webpack/runtime/define property getters */
/******/ (() => {
/******/ // define getter functions for harmony exports
/******/ __webpack_require__.d = (exports, definition) => {
/******/ for(var key in definition) {
/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ }
/******/ }
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/ensure chunk */
/******/ (() => {
/******/ __webpack_require__.f = {};
/******/ // This file contains only the entry chunk.
/******/ // The chunk loading function for additional chunks
/******/ __webpack_require__.e = (chunkId) => {
/******/ return Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {
/******/ __webpack_require__.f[key](chunkId, promises);
/******/ return promises;
/******/ }, []));
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/get javascript chunk filename */
/******/ (() => {
/******/ // This function allow to reference async chunks
/******/ __webpack_require__.u = (chunkId) => {
/******/ // return url for filenames not based on template
/******/ if (chunkId === 631) return "workers/fibonacci.js";
/******/ // return url for filenames based on template
/******/ return "" + (chunkId === 348 ? "chat" : chunkId) + ".js";
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/hasOwnProperty shorthand */
/******/ (() => {
/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ })();
/******/
/******/ /* webpack/runtime/make namespace object */
/******/ (() => {
/******/ // define __esModule on exports
/******/ __webpack_require__.r = (exports) => {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/publicPath */
/******/ (() => {
/******/ __webpack_require__.p = "/dist/";
/******/ })();
/******/
/******/ /* webpack/runtime/import chunk loading */
/******/ (() => {
/******/ __webpack_require__.b = new URL("./", import.meta.url);
/******/
/******/ // object to store loaded and loading chunks
/******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched
/******/ // [resolve, reject, Promise] = chunk loading, 0 = chunk loaded
/******/ var installedChunks = {
/******/ 179: 0
/******/ };
/******/
/******/ __webpack_require__.f.j = (chunkId, promises) => {
/******/ // import() chunk loading for javascript
/******/ var installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;
/******/ if(installedChunkData !== 0) { // 0 means "already installed".
/******/
/******/ // a Promise means "currently loading".
/******/ if(installedChunkData) {
/******/ promises.push(installedChunkData[1]);
/******/ } else {
/******/ if(true) { // all chunks have JS
/******/ // setup Promise in chunk cache
/******/ var promise = import("./" + __webpack_require__.u(chunkId)).then((data) => {
/******/ var {ids, modules, runtime} = data;
/******/ // add "modules" to the modules object,
/******/ // then flag all "ids" as loaded and fire callback
/******/ var moduleId, chunkId, i = 0;
/******/ for(moduleId in modules) {
/******/ if(__webpack_require__.o(modules, moduleId)) {
/******/ __webpack_require__.m[moduleId] = modules[moduleId];
/******/ }
/******/ }
/******/ if(runtime) runtime(__webpack_require__);
/******/ for(;i < ids.length; i++) {
/******/ chunkId = ids[i];
/******/ if(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {
/******/ installedChunks[chunkId][0]();
/******/ }
/******/ installedChunks[ids[i]] = 0;
/******/ }
/******/
/******/ }, (e) => {
/******/ if(installedChunks[chunkId] !== 0) installedChunks[chunkId] = undefined;
/******/ throw e;
/******/ });
/******/ var promise = Promise.race([promise, new Promise((resolve) => (installedChunkData = installedChunks[chunkId] = [resolve]))])
/******/ promises.push(installedChunkData[1] = promise);
/******/ } else installedChunks[chunkId] = 0;
/******/ }
/******/ }
/******/ };
/******/
/******/ // no on chunks loaded
/******/ })();
/******/
/************************************************************************/
```
</details>
``` js
var __webpack_exports__ = {};
/*!********************!*\
!*** ./example.js ***!
\********************/
/*! unknown exports (runtime-defined) */
/*! runtime requirements: __webpack_require__.p, __webpack_require__.b, __webpack_require__.u, __webpack_require__.e, __webpack_require__, __webpack_require__.* */
document.body.innerHTML = `
<pre id="history"></pre>
<form>
<input id="message" type="text">
<button id="send">Send Message</button>
</form>
<p>Computing fibonacci without worker:</p>
<input id="fib1" type="number">
<pre id="output1"></pre>
<p>Computing fibonacci with worker:</p>
<input id="fib2" type="number">
<pre id="output2"></pre>
`;
const history = document.getElementById("history");
const message = document.getElementById("message");
const send = document.getElementById("send");
const fib1 = document.getElementById("fib1");
const output1 = document.getElementById("output1");
const fib2 = document.getElementById("fib2");
const output2 = document.getElementById("output2");
/// CHAT with shared worker ///
const chatWorker = new SharedWorker(
new URL(/* worker import */ __webpack_require__.p + __webpack_require__.u(348), __webpack_require__.b),
{
name: "chat",
type: "module"
}
);
let historyTimeout;
const scheduleUpdateHistory = () => {
clearTimeout(historyTimeout);
historyTimeout = setTimeout(() => {
chatWorker.port.postMessage({ type: "history" });
}, 1000);
};
scheduleUpdateHistory();
const from = `User ${Math.floor(Math.random() * 10000)}`;
send.addEventListener("click", e => {
chatWorker.port.postMessage({
type: "message",
content: message.value,
from
});
message.value = "";
message.focus();
e.preventDefault();
});
chatWorker.port.onmessage = event => {
const msg = event.data;
switch (msg.type) {
case "history":
history.innerText = msg.history.join("\n");
scheduleUpdateHistory();
break;
}
};
/// FIBONACCI without worker ///
fib1.addEventListener("change", async () => {
try {
const value = parseInt(fib1.value, 10);
const { fibonacci } = await __webpack_require__.e(/*! import() */ 129).then(__webpack_require__.bind(__webpack_require__, /*! ./fibonacci */ 2));
const result = fibonacci(value);
output1.innerText = `fib(${value}) = ${result}`;
} catch (e) {
output1.innerText = e.message;
}
});
/// FIBONACCI with worker ///
const fibWorker = new Worker(new URL(/* worker import */ __webpack_require__.p + __webpack_require__.u(631), __webpack_require__.b), {
name: "fibonacci",
type: "module"
/* webpackEntryOptions: { filename: "workers/[name].js" } */
});
fib2.addEventListener("change", () => {
try {
const value = parseInt(fib2.value, 10);
fibWorker.postMessage(`${value}`);
} catch (e) {
output2.innerText = e.message;
}
});
fibWorker.onmessage = event => {
output2.innerText = event.data;
};
```
# dist/chat.js
```javascript
/******/ var __webpack_modules__ = ({});
```
<details><summary><code>/* webpack runtime code */</code></summary>
``` js
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ // no module.id needed
/******/ // no module.loaded needed
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = __webpack_modules__;
/******/
/************************************************************************/
/******/ /* webpack/runtime/define property getters */
/******/ (() => {
/******/ // define getter functions for harmony exports
/******/ __webpack_require__.d = (exports, definition) => {
/******/ for(var key in definition) {
/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ }
/******/ }
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/ensure chunk */
/******/ (() => {
/******/ __webpack_require__.f = {};
/******/ // This file contains only the entry chunk.
/******/ // The chunk loading function for additional chunks
/******/ __webpack_require__.e = (chunkId) => {
/******/ return Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {
/******/ __webpack_require__.f[key](chunkId, promises);
/******/ return promises;
/******/ }, []));
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/get javascript chunk filename */
/******/ (() => {
/******/ // This function allow to reference async chunks
/******/ __webpack_require__.u = (chunkId) => {
/******/ // return url for filenames based on template
/******/ return "" + chunkId + ".js";
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/hasOwnProperty shorthand */
/******/ (() => {
/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ })();
/******/
/******/ /* webpack/runtime/make namespace object */
/******/ (() => {
/******/ // define __esModule on exports
/******/ __webpack_require__.r = (exports) => {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/import chunk loading */
/******/ (() => {
/******/ // no baseURI
/******/
/******/ // object to store loaded and loading chunks
/******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched
/******/ // [resolve, reject, Promise] = chunk loading, 0 = chunk loaded
/******/ var installedChunks = {
/******/ 348: 0
/******/ };
/******/
/******/ __webpack_require__.f.j = (chunkId, promises) => {
/******/ // import() chunk loading for javascript
/******/ var installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;
/******/ if(installedChunkData !== 0) { // 0 means "already installed".
/******/
/******/ // a Promise means "currently loading".
/******/ if(installedChunkData) {
/******/ promises.push(installedChunkData[1]);
/******/ } else {
/******/ if(true) { // all chunks have JS
/******/ // setup Promise in chunk cache
/******/ var promise = import("./" + __webpack_require__.u(chunkId)).then((data) => {
/******/ var {ids, modules, runtime} = data;
/******/ // add "modules" to the modules object,
/******/ // then flag all "ids" as loaded and fire callback
/******/ var moduleId, chunkId, i = 0;
/******/ for(moduleId in modules) {
/******/ if(__webpack_require__.o(modules, moduleId)) {
/******/ __webpack_require__.m[moduleId] = modules[moduleId];
/******/ }
/******/ }
/******/ if(runtime) runtime(__webpack_require__);
/******/ for(;i < ids.length; i++) {
/******/ chunkId = ids[i];
/******/ if(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {
/******/ installedChunks[chunkId][0]();
/******/ }
/******/ installedChunks[ids[i]] = 0;
/******/ }
/******/
/******/ }, (e) => {
/******/ if(installedChunks[chunkId] !== 0) installedChunks[chunkId] = undefined;
/******/ throw e;
/******/ });
/******/ var promise = Promise.race([promise, new Promise((resolve) => (installedChunkData = installedChunks[chunkId] = [resolve]))])
/******/ promises.push(installedChunkData[1] = promise);
/******/ } else installedChunks[chunkId] = 0;
/******/ }
/******/ }
/******/ };
/******/
/******/ // no on chunks loaded
/******/ })();
/******/
/************************************************************************/
```
</details>
``` js
var __webpack_exports__ = {};
/*!************************!*\
!*** ./chat-worker.js ***!
\************************/
/*! unknown exports (runtime-defined) */
/*! runtime requirements: __webpack_require__.e, __webpack_require__, __webpack_require__.* */
onconnect = function (e) {
for (const port of e.ports) {
port.onmessage = async event => {
const msg = event.data;
switch (msg.type) {
case "message":
const { add } = await __webpack_require__.e(/*! import() */ 192).then(__webpack_require__.bind(__webpack_require__, /*! ./chat-module */ 4));
add(msg.content, msg.from);
// fallthrough
case "history":
const { history } = await __webpack_require__.e(/*! import() */ 192).then(__webpack_require__.bind(__webpack_require__, /*! ./chat-module */ 4));
port.postMessage({
type: "history",
history
});
break;
}
};
}
};
```
```javascript
var e,o={},t={};function r(e){var n=t[e];if(void 0!==n)return n.exports;var s=t[e]={exports:{}};return o[e](s,s.exports,r),s.exports}r.m=o,r.d=(e,o)=>{for(var t in o)r.o(o,t)&&!r.o(e,t)&&Object.defineProperty(e,t,{enumerable:!0,get:o[t]})},r.f={},r.e=e=>Promise.all(Object.keys(r.f).reduce(((o,t)=>(r.f[t](e,o),o)),[])),r.u=e=>e+".js",r.o=(e,o)=>Object.prototype.hasOwnProperty.call(e,o),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},e={348:0},r.f.j=(o,t)=>{var n=r.o(e,o)?e[o]:void 0;if(0!==n)if(n)t.push(n[1]);else{var s=import("./"+r.u(o)).then((o=>{var t,n,{ids:s,modules:i,runtime:a}=o,c=0;for(t in i)r.o(i,t)&&(r.m[t]=i[t]);for(a&&a(r);c<s.length;c++)n=s[c],r.o(e,n)&&e[n]&&e[n][0](),e[s[c]]=0}),(t=>{throw 0!==e[o]&&(e[o]=void 0),t}));s=Promise.race([s,new Promise((t=>n=e[o]=[t]))]),t.push(n[1]=s)}},onconnect=function(e){for(const o of e.ports)o.onmessage=async e=>{const t=e.data;switch(t.type){case"message":const{add:e}=await r.e(192).then(r.bind(r,192));e(t.content,t.from);case"history":const{history:n}=await r.e(192).then(r.bind(r,192));o.postMessage({type:"history",history:n})}}};
```
# dist/workers/fibonacci.js
```javascript
/******/ var __webpack_modules__ = ({});
```
<details><summary><code>/* webpack runtime code */</code></summary>
``` js
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ // no module.id needed
/******/ // no module.loaded needed
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = __webpack_modules__;
/******/
/************************************************************************/
/******/ /* webpack/runtime/define property getters */
/******/ (() => {
/******/ // define getter functions for harmony exports
/******/ __webpack_require__.d = (exports, definition) => {
/******/ for(var key in definition) {
/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ }
/******/ }
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/ensure chunk */
/******/ (() => {
/******/ __webpack_require__.f = {};
/******/ // This file contains only the entry chunk.
/******/ // The chunk loading function for additional chunks
/******/ __webpack_require__.e = (chunkId) => {
/******/ return Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {
/******/ __webpack_require__.f[key](chunkId, promises);
/******/ return promises;
/******/ }, []));
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/get javascript chunk filename */
/******/ (() => {
/******/ // This function allow to reference async chunks
/******/ __webpack_require__.u = (chunkId) => {
/******/ // return url for filenames based on template
/******/ return "" + chunkId + ".js";
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/hasOwnProperty shorthand */
/******/ (() => {
/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ })();
/******/
/******/ /* webpack/runtime/make namespace object */
/******/ (() => {
/******/ // define __esModule on exports
/******/ __webpack_require__.r = (exports) => {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/import chunk loading */
/******/ (() => {
/******/ // no baseURI
/******/
/******/ // object to store loaded and loading chunks
/******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched
/******/ // [resolve, reject, Promise] = chunk loading, 0 = chunk loaded
/******/ var installedChunks = {
/******/ 631: 0
/******/ };
/******/
/******/ __webpack_require__.f.j = (chunkId, promises) => {
/******/ // import() chunk loading for javascript
/******/ var installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;
/******/ if(installedChunkData !== 0) { // 0 means "already installed".
/******/
/******/ // a Promise means "currently loading".
/******/ if(installedChunkData) {
/******/ promises.push(installedChunkData[1]);
/******/ } else {
/******/ if(true) { // all chunks have JS
/******/ // setup Promise in chunk cache
/******/ var promise = import("../" + __webpack_require__.u(chunkId)).then((data) => {
/******/ var {ids, modules, runtime} = data;
/******/ // add "modules" to the modules object,
/******/ // then flag all "ids" as loaded and fire callback
/******/ var moduleId, chunkId, i = 0;
/******/ for(moduleId in modules) {
/******/ if(__webpack_require__.o(modules, moduleId)) {
/******/ __webpack_require__.m[moduleId] = modules[moduleId];
/******/ }
/******/ }
/******/ if(runtime) runtime(__webpack_require__);
/******/ for(;i < ids.length; i++) {
/******/ chunkId = ids[i];
/******/ if(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {
/******/ installedChunks[chunkId][0]();
/******/ }
/******/ installedChunks[ids[i]] = 0;
/******/ }
/******/
/******/ }, (e) => {
/******/ if(installedChunks[chunkId] !== 0) installedChunks[chunkId] = undefined;
/******/ throw e;
/******/ });
/******/ var promise = Promise.race([promise, new Promise((resolve) => (installedChunkData = installedChunks[chunkId] = [resolve]))])
/******/ promises.push(installedChunkData[1] = promise);
/******/ } else installedChunks[chunkId] = 0;
/******/ }
/******/ }
/******/ };
/******/
/******/ // no on chunks loaded
/******/ })();
/******/
/************************************************************************/
```
</details>
``` js
var __webpack_exports__ = {};
/*!***********************!*\
!*** ./fib-worker.js ***!
\***********************/
/*! unknown exports (runtime-defined) */
/*! runtime requirements: __webpack_require__.e, __webpack_require__, __webpack_require__.* */
onmessage = async event => {
const { fibonacci } = await __webpack_require__.e(/*! import() */ 129).then(__webpack_require__.bind(__webpack_require__, /*! ./fibonacci */ 2));
const value = JSON.parse(event.data);
postMessage(`fib(${value}) = ${fibonacci(value)}`);
};
```
```javascript
var e,o={},r={};function t(e){var i=r[e];if(void 0!==i)return i.exports;var a=r[e]={exports:{}};return o[e](a,a.exports,t),a.exports}t.m=o,t.d=(e,o)=>{for(var r in o)t.o(o,r)&&!t.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:o[r]})},t.f={},t.e=e=>Promise.all(Object.keys(t.f).reduce(((o,r)=>(t.f[r](e,o),o)),[])),t.u=e=>e+".js",t.o=(e,o)=>Object.prototype.hasOwnProperty.call(e,o),t.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},e={631:0},t.f.j=(o,r)=>{var i=t.o(e,o)?e[o]:void 0;if(0!==i)if(i)r.push(i[1]);else{var a=import("../"+t.u(o)).then((o=>{var r,i,{ids:a,modules:n,runtime:s}=o,f=0;for(r in n)t.o(n,r)&&(t.m[r]=n[r]);for(s&&s(t);f<a.length;f++)i=a[f],t.o(e,i)&&e[i]&&e[i][0](),e[a[f]]=0}),(r=>{throw 0!==e[o]&&(e[o]=void 0),r}));a=Promise.race([a,new Promise((r=>i=e[o]=[r]))]),r.push(i[1]=a)}},onmessage=async e=>{const{fibonacci:o}=await t.e(129).then(t.bind(t,129)),r=JSON.parse(e.data);postMessage(`fib(${r}) = ${o(r)}`)};
```
# dist/129.js
```javascript
export const id = 129;
export const ids = [129];
export const modules = {
/***/ 2:
/*!**********************!*\
!*** ./fibonacci.js ***!
\**********************/
/*! namespace exports */
/*! export fibonacci [provided] [no usage info] [missing usage info prevents renaming] */
/*! other exports [not provided] [no usage info] */
/*! runtime requirements: __webpack_require__.r, __webpack_exports__, __webpack_require__.d, __webpack_require__.* */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "fibonacci": () => (/* binding */ fibonacci)
/* harmony export */ });
function fibonacci(n) {
return n < 1 ? 0 : n <= 2 ? 1 : fibonacci(n - 1) + fibonacci(n - 2);
}
/***/ })
};
;
```
# Info
## Unoptimized
```
asset main.js 8.54 KiB [emitted] [javascript module] (name: main)
asset chat.js 6.33 KiB [emitted] [javascript module] (name: chat)
asset workers/fibonacci.js 5.97 KiB [emitted] [javascript module] (name: fibonacci)
asset 192.js 1.02 KiB [emitted] [javascript module]
asset 129.js 862 bytes [emitted] [javascript module]
chunk (runtime: 9a81d90cfd0dfd13d748, main) 129.js 103 bytes [rendered]
> ./fibonacci ./example.js 70:30-51
> ./fibonacci ./fib-worker.js 2:29-50
./fibonacci.js 103 bytes [built] [code generated]
[exports: fibonacci]
[used exports unknown]
import() ./fibonacci ./example.js 70:30-51
import() ./fibonacci ./fib-worker.js 2:29-50
chunk (runtime: main) main.js (main) 2.25 KiB (javascript) 3.09 KiB (runtime) [entry] [rendered]
> ./example.js main
runtime modules 3.09 KiB 7 modules
./example.js 2.25 KiB [built] [code generated]
[used exports unknown]
entry ./example.js main
chunk (runtime: 1fad8bf8de78b0a77bfd) 192.js 152 bytes [rendered]
> ./chat-module ./chat-worker.js 11:31-54
> ./chat-module ./chat-worker.js 7:27-50
./chat-module.js 152 bytes [built] [code generated]
[exports: add, history]
[used exports unknown]
import() ./chat-module ./chat-worker.js 7:27-50
import() ./chat-module ./chat-worker.js 11:31-54
chunk (runtime: 1fad8bf8de78b0a77bfd) chat.js (chat) 442 bytes (javascript) 2.89 KiB (runtime) [entry] [rendered]
> ./example.js 25:19-31:1
runtime modules 2.89 KiB 6 modules
./chat-worker.js 442 bytes [built] [code generated]
[used exports unknown]
new Worker() ./chat-worker.js ./example.js 25:19-31:1
chunk (runtime: 9a81d90cfd0dfd13d748) workers/fibonacci.js (fibonacci) 176 bytes (javascript) 2.89 KiB (runtime) [entry] [rendered]
> ./example.js 80:18-84:2
runtime modules 2.89 KiB 6 modules
./fib-worker.js 176 bytes [built] [code generated]
[used exports unknown]
new Worker() ./fib-worker.js ./example.js 80:18-84:2
webpack 5.40.0 compiled successfully
```
## Production mode
```
asset main.js 2.5 KiB [emitted] [javascript module] [minimized] (name: main)
asset chat.js 1.19 KiB [emitted] [javascript module] [minimized] (name: chat)
asset workers/fibonacci.js 1.04 KiB [emitted] [javascript module] [minimized] (name: fibonacci)
asset 192.js 187 bytes [emitted] [javascript module] [minimized]
asset 129.js 161 bytes [emitted] [javascript module] [minimized]
chunk (runtime: 9a81d90cfd0dfd13d748, main) 129.js 103 bytes [rendered]
> ./fibonacci ./example.js 70:30-51
> ./fibonacci ./fib-worker.js 2:29-50
./fibonacci.js 103 bytes [built] [code generated]
[exports: fibonacci]
import() ./fibonacci ./example.js 70:30-51
import() ./fibonacci ./fib-worker.js 2:29-50
chunk (runtime: main) main.js (main) 2.25 KiB (javascript) 3.09 KiB (runtime) [entry] [rendered]
> ./example.js main
runtime modules 3.09 KiB 7 modules
./example.js 2.25 KiB [built] [code generated]
[no exports used]
entry ./example.js main
chunk (runtime: 1fad8bf8de78b0a77bfd) 192.js 152 bytes [rendered]
> ./chat-module ./chat-worker.js 11:31-54
> ./chat-module ./chat-worker.js 7:27-50
./chat-module.js 152 bytes [built] [code generated]
[exports: add, history]
import() ./chat-module ./chat-worker.js 7:27-50
import() ./chat-module ./chat-worker.js 11:31-54
chunk (runtime: 1fad8bf8de78b0a77bfd) chat.js (chat) 442 bytes (javascript) 2.89 KiB (runtime) [entry] [rendered]
> ./example.js 25:19-31:1
runtime modules 2.89 KiB 6 modules
./chat-worker.js 442 bytes [built] [code generated]
[no exports used]
new Worker() ./chat-worker.js ./example.js 25:19-31:1
chunk (runtime: 9a81d90cfd0dfd13d748) workers/fibonacci.js (fibonacci) 176 bytes (javascript) 2.89 KiB (runtime) [entry] [rendered]
> ./example.js 80:18-84:2
runtime modules 2.89 KiB 6 modules
./fib-worker.js 176 bytes [built] [code generated]
[no exports used]
new Worker() ./fib-worker.js ./example.js 80:18-84:2
webpack 5.40.0 compiled successfully
```

View File

@ -0,0 +1,3 @@
global.NO_TARGET_ARGS = true;
global.NO_PUBLIC_PATH = true;
require("../build-common");

View File

@ -0,0 +1,6 @@
export const history = [];
export const add = (content, from) => {
if (history.length > 10) history.shift();
history.push(`${from}: ${content}`);
};

View File

@ -0,0 +1,20 @@
onconnect = function (e) {
for (const port of e.ports) {
port.onmessage = async event => {
const msg = event.data;
switch (msg.type) {
case "message":
const { add } = await import("./chat-module");
add(msg.content, msg.from);
// fallthrough
case "history":
const { history } = await import("./chat-module");
port.postMessage({
type: "history",
history
});
break;
}
};
}
};

View File

@ -0,0 +1,97 @@
document.body.innerHTML = `
<pre id="history"></pre>
<form>
<input id="message" type="text">
<button id="send">Send Message</button>
</form>
<p>Computing fibonacci without worker:</p>
<input id="fib1" type="number">
<pre id="output1"></pre>
<p>Computing fibonacci with worker:</p>
<input id="fib2" type="number">
<pre id="output2"></pre>
`;
const history = document.getElementById("history");
const message = document.getElementById("message");
const send = document.getElementById("send");
const fib1 = document.getElementById("fib1");
const output1 = document.getElementById("output1");
const fib2 = document.getElementById("fib2");
const output2 = document.getElementById("output2");
/// CHAT with shared worker ///
const chatWorker = new SharedWorker(
new URL("./chat-worker.js", import.meta.url),
{
name: "chat",
type: "module"
}
);
let historyTimeout;
const scheduleUpdateHistory = () => {
clearTimeout(historyTimeout);
historyTimeout = setTimeout(() => {
chatWorker.port.postMessage({ type: "history" });
}, 1000);
};
scheduleUpdateHistory();
const from = `User ${Math.floor(Math.random() * 10000)}`;
send.addEventListener("click", e => {
chatWorker.port.postMessage({
type: "message",
content: message.value,
from
});
message.value = "";
message.focus();
e.preventDefault();
});
chatWorker.port.onmessage = event => {
const msg = event.data;
switch (msg.type) {
case "history":
history.innerText = msg.history.join("\n");
scheduleUpdateHistory();
break;
}
};
/// FIBONACCI without worker ///
fib1.addEventListener("change", async () => {
try {
const value = parseInt(fib1.value, 10);
const { fibonacci } = await import("./fibonacci");
const result = fibonacci(value);
output1.innerText = `fib(${value}) = ${result}`;
} catch (e) {
output1.innerText = e.message;
}
});
/// FIBONACCI with worker ///
const fibWorker = new Worker(new URL("./fib-worker.js", import.meta.url), {
name: "fibonacci",
type: "module"
/* webpackEntryOptions: { filename: "workers/[name].js" } */
});
fib2.addEventListener("change", () => {
try {
const value = parseInt(fib2.value, 10);
fibWorker.postMessage(`${value}`);
} catch (e) {
output2.innerText = e.message;
}
});
fibWorker.onmessage = event => {
output2.innerText = event.data;
};

View File

@ -0,0 +1,5 @@
onmessage = async event => {
const { fibonacci } = await import("./fibonacci");
const value = JSON.parse(event.data);
postMessage(`fib(${value}) = ${fibonacci(value)}`);
};

View File

@ -0,0 +1,3 @@
export function fibonacci(n) {
return n < 1 ? 0 : n <= 2 ? 1 : fibonacci(n - 1) + fibonacci(n - 2);
}

View File

@ -0,0 +1,10 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Worker example</title>
</head>
<body>
<script src="./dist/main.js" async type="module"></script>
</body>
</html>

View File

@ -0,0 +1,75 @@
# example.js
```javascript
_{{example.js}}_
```
# fib-worker.js
```javascript
_{{fib-worker.js}}_
```
# fibonacci.js
```javascript
_{{fibonacci.js}}_
```
# chat-worker.js
```javascript
_{{chat-worker.js}}_
```
# chat-module.js
```javascript
_{{chat-module.js}}_
```
# dist/main.js
```javascript
_{{dist/main.js}}_
```
# dist/chat.js
```javascript
_{{dist/chat.js}}_
```
```javascript
_{{production:dist/chat.js}}_
```
# dist/workers/fibonacci.js
```javascript
_{{dist/workers/fibonacci.js}}_
```
```javascript
_{{production:dist/workers/fibonacci.js}}_
```
# dist/129.js
```javascript
_{{dist/129.js}}_
```
# Info
## Unoptimized
```
_{{stdout}}_
```
## Production mode
```
_{{production:stdout}}_
```

View File

@ -0,0 +1,18 @@
var path = require("path");
module.exports = {
entry: "./example.js",
output: {
path: path.join(__dirname, "dist"),
filename: "[name].js",
chunkFilename: "[name].js",
publicPath: "/dist/"
},
optimization: {
chunkIds: "deterministic" // To keep filename consistent between different modes (for example building only)
},
target: "browserslist: last 2 Chrome versions",
experiments: {
outputModule: true
}
};

View File

@ -367,7 +367,7 @@ export const add = (content, from) => {
/******/ __webpack_require__.m[moduleId] = moreModules[moduleId];
/******/ }
/******/ }
/******/ if(runtime) runtime(__webpack_require__);
/******/ if(runtime) var result = runtime(__webpack_require__);
/******/ if(parentChunkLoadingFunction) parentChunkLoadingFunction(data);
/******/ for(;i < chunkIds.length; i++) {
/******/ chunkId = chunkIds[i];
@ -721,8 +721,8 @@ onmessage = async event => {
!*** ./fibonacci.js ***!
\**********************/
/*! namespace exports */
/*! export fibonacci [provided] [maybe used in main, ./example.js|80:18-84:2 (runtime-defined)] [usage prevents renaming] */
/*! other exports [not provided] [maybe used in main, ./example.js|80:18-84:2 (runtime-defined)] */
/*! export fibonacci [provided] [maybe used in main, 9a81d90cfd0dfd13d748 (runtime-defined)] [usage prevents renaming] */
/*! other exports [not provided] [maybe used in main, 9a81d90cfd0dfd13d748 (runtime-defined)] */
/*! runtime requirements: __webpack_require__.r, __webpack_exports__, __webpack_require__.d, __webpack_require__.* */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
@ -746,36 +746,36 @@ function fibonacci(n) {
## Unoptimized
```
asset main.js 12.2 KiB [emitted] (name: main)
asset main.js 12.3 KiB [emitted] (name: main)
asset workers/fibonacci.js 5.43 KiB [emitted] (name: fibonacci)
asset 129.js 937 bytes [emitted]
asset 129.js 931 bytes [emitted]
asset chat.js 911 bytes [emitted] (name: chat)
chunk (runtime: ./example.js|80:18-84:2, main) 129.js 103 bytes [rendered]
chunk (runtime: 9a81d90cfd0dfd13d748, main) 129.js 103 bytes [rendered]
> ./fibonacci ./example.js 70:30-51
> ./fibonacci ./fib-worker.js 2:29-50
./fibonacci.js 103 bytes [built] [code generated]
[exports: fibonacci]
import() ./fibonacci ./example.js 70:30-51
import() ./fibonacci ./fib-worker.js 2:29-50
chunk (runtime: main) main.js (main) 2.25 KiB (javascript) 5.64 KiB (runtime) [entry] [rendered]
chunk (runtime: main) main.js (main) 2.25 KiB (javascript) 5.65 KiB (runtime) [entry] [rendered]
> ./example.js main
runtime modules 5.64 KiB 8 modules
runtime modules 5.65 KiB 8 modules
./example.js 2.25 KiB [built] [code generated]
[no exports used]
entry ./example.js main
chunk (runtime: ./example.js|25:19-31:1) chat.js (chat) 527 bytes [entry] [rendered]
chunk (runtime: 1fad8bf8de78b0a77bfd) chat.js (chat) 527 bytes [entry] [rendered]
> ./example.js 25:19-31:1
./chat-worker.js + 1 modules 527 bytes [built] [code generated]
[no exports]
[no exports used]
new Worker() ./chat-worker.js ./example.js 25:19-31:1
chunk (runtime: ./example.js|80:18-84:2) workers/fibonacci.js (fibonacci) 176 bytes (javascript) 2.14 KiB (runtime) [entry] [rendered]
chunk (runtime: 9a81d90cfd0dfd13d748) workers/fibonacci.js (fibonacci) 176 bytes (javascript) 2.14 KiB (runtime) [entry] [rendered]
> ./example.js 80:18-84:2
runtime modules 2.14 KiB 7 modules
./fib-worker.js 176 bytes [built] [code generated]
[no exports used]
new Worker() ./fib-worker.js ./example.js 80:18-84:2
webpack 5.27.2 compiled successfully
webpack 5.40.0 compiled successfully
```
## Production mode
@ -785,30 +785,30 @@ asset main.js 3.44 KiB [emitted] [minimized] (name: main)
asset workers/fibonacci.js 945 bytes [emitted] [minimized] (name: fibonacci)
asset chat.js 270 bytes [emitted] [minimized] (name: chat)
asset 129.js 166 bytes [emitted] [minimized]
chunk (runtime: ./example.js|80:18-84:2, main) 129.js 103 bytes [rendered]
chunk (runtime: 9a81d90cfd0dfd13d748, main) 129.js 103 bytes [rendered]
> ./fibonacci ./example.js 70:30-51
> ./fibonacci ./fib-worker.js 2:29-50
./fibonacci.js 103 bytes [built] [code generated]
[exports: fibonacci]
import() ./fibonacci ./example.js 70:30-51
import() ./fibonacci ./fib-worker.js 2:29-50
chunk (runtime: main) main.js (main) 2.25 KiB (javascript) 5.64 KiB (runtime) [entry] [rendered]
chunk (runtime: main) main.js (main) 2.25 KiB (javascript) 5.65 KiB (runtime) [entry] [rendered]
> ./example.js main
runtime modules 5.64 KiB 8 modules
runtime modules 5.65 KiB 8 modules
./example.js 2.25 KiB [built] [code generated]
[no exports used]
entry ./example.js main
chunk (runtime: ./example.js|25:19-31:1) chat.js (chat) 527 bytes [entry] [rendered]
chunk (runtime: 1fad8bf8de78b0a77bfd) chat.js (chat) 527 bytes [entry] [rendered]
> ./example.js 25:19-31:1
./chat-worker.js + 1 modules 527 bytes [built] [code generated]
[no exports]
[no exports used]
new Worker() ./chat-worker.js ./example.js 25:19-31:1
chunk (runtime: ./example.js|80:18-84:2) workers/fibonacci.js (fibonacci) 176 bytes (javascript) 2.14 KiB (runtime) [entry] [rendered]
chunk (runtime: 9a81d90cfd0dfd13d748) workers/fibonacci.js (fibonacci) 176 bytes (javascript) 2.14 KiB (runtime) [entry] [rendered]
> ./example.js 80:18-84:2
runtime modules 2.14 KiB 7 modules
./fib-worker.js 176 bytes [built] [code generated]
[no exports used]
new Worker() ./fib-worker.js ./example.js 80:18-84:2
webpack 5.27.2 compiled successfully
webpack 5.40.0 compiled successfully
```

View File

@ -318,7 +318,8 @@ class WebpackOptionsApply extends OptionsApply {
new URLPlugin().apply(compiler);
new WorkerPlugin(
options.output.workerChunkLoading,
options.output.workerWasmLoading
options.output.workerWasmLoading,
options.output.module
).apply(compiler);
new DefaultStatsFactoryPlugin().apply(compiler);

View File

@ -48,9 +48,10 @@ const DEFAULT_SYNTAX = [
const workerIndexMap = new WeakMap();
class WorkerPlugin {
constructor(chunkLoading, wasmLoading) {
constructor(chunkLoading, wasmLoading, module) {
this._chunkLoading = chunkLoading;
this._wasmLoading = wasmLoading;
this._module = module;
}
/**
* Apply the plugin
@ -311,31 +312,45 @@ class WorkerPlugin {
if (expressions.type) {
const expr = expressions.type;
if (options.type !== false) {
const dep = new ConstDependency("undefined", expr.range);
const dep = new ConstDependency(
this._module ? '"module"' : "undefined",
expr.range
);
dep.loc = expr.loc;
parser.state.module.addPresentationalDependency(dep);
expressions.type = undefined;
}
} else if (hasSpreadInOptions && insertType === "comma") {
const dep = new ConstDependency(
", type: undefined",
insertLocation
);
dep.loc = expr.loc;
parser.state.module.addPresentationalDependency(dep);
} else if (insertType === "comma") {
if (this._module || hasSpreadInOptions) {
const dep = new ConstDependency(
`, type: ${this._module ? '"module"' : "undefined"}`,
insertLocation
);
dep.loc = expr.loc;
parser.state.module.addPresentationalDependency(dep);
}
} else if (insertType === "spread") {
const dep1 = new ConstDependency(
"Object.assign({}, ",
insertLocation[0]
);
const dep2 = new ConstDependency(
", { type: undefined })",
`, { type: ${this._module ? '"module"' : "undefined"} })`,
insertLocation[1]
);
dep1.loc = expr.loc;
dep2.loc = expr.loc;
parser.state.module.addPresentationalDependency(dep1);
parser.state.module.addPresentationalDependency(dep2);
} else if (insertType === "argument") {
if (this._module) {
const dep = new ConstDependency(
', { type: "module" }',
insertLocation
);
dep.loc = expr.loc;
parser.state.module.addPresentationalDependency(dep);
}
}
parser.walkExpression(expr.callee);

View File

@ -116,7 +116,7 @@ class ModuleChunkLoadingRuntimeModule extends RuntimeModule {
"chunkId, promises",
hasJsMatcher !== false
? Template.indent([
"// JSONP chunk loading for javascript",
"// import() chunk loading for javascript",
`var installedChunkData = ${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;`,
'if(installedChunkData !== 0) { // 0 means "already installed".',
Template.indent([