diff --git a/.editorconfig b/.editorconfig
index 07e49a0e38b..0c2b037f084 100644
--- a/.editorconfig
+++ b/.editorconfig
@@ -12,14 +12,14 @@ max_line_length = 80
indent_style = space
indent_size = 2
-[test/cases/parsing/bom/bomfile.{css,js}]
-charset = utf-8-bom
-
-[test/configCases/css/no-extra-runtime-in-js/source.text]
-insert_final_newline = false
-
[*.md]
trim_trailing_whitespace = false
[*.snap]
trim_trailing_whitespace = false
+
+[test/cases/parsing/bom/bomfile.{css,js}]
+charset = utf-8-bom
+
+[test/configCases/css/no-extra-runtime-in-js/source.text]
+insert_final_newline = false
diff --git a/.prettierrc.js b/.prettierrc.js
index b8110f9cd35..04b93b8c6a7 100644
--- a/.prettierrc.js
+++ b/.prettierrc.js
@@ -5,7 +5,7 @@ module.exports = {
useTabs: true,
tabWidth: 2,
trailingComma: "none",
- arrowParens: "avoid",
+ arrowParens: "always",
overrides: [
{
files: "*.json",
diff --git a/README.md b/README.md
index 2149c2f2126..a4b1440cbef 100644
--- a/README.md
+++ b/README.md
@@ -133,16 +133,6 @@ loaders](https://webpack.js.org/api/loaders/) using Node.js.
Loaders are activated by using `loadername!` prefixes in `require()` statements,
or are automatically applied via regex from your webpack configuration.
-#### Files
-
-| Name | Status | Install Size | Description |
-| :---------------: | :--------: | :----------: | :------------------------------------------------------- |
-| [val-loader][val] | ![val-npm] | ![val-size] | Executes code as module and considers exports as JS code |
-
-[val]: https://github.com/webpack-contrib/val-loader
-[val-npm]: https://img.shields.io/npm/v/val-loader.svg
-[val-size]: https://packagephobia.com/badge?p=val-loader
-
#### JSON
| Name | Status | Install Size | Description |
@@ -262,6 +252,18 @@ you full control of what is loaded initially and what is loaded at runtime
through code splitting. It can also make your code chunks **cache
friendly** by using hashes.
+### Developer Tools
+
+If you're working on webpack itself, or building advanced plugins or integrations, the tools below can help you explore internal mechanics, debug plugin life-cycles, and build custom tooling.
+
+#### Instrumentation
+
+| Name | Status | Description |
+| --------------------------------------------------------- | --------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
+| [tapable-tracer](https://github.com/ertgl/tapable-tracer) | ![tapable-tracer-npm] | Traces tapable hook execution in real-time and collects structured stack frames. Can export to UML for generating visualizations. |
+
+[tapable-tracer-npm]: https://img.shields.io/npm/v/tapable-tracer.svg
+
Contributing
**We want contributing to webpack to be fun, enjoyable, and educational for anyone, and everyone.** We have a [vibrant ecosystem](https://medium.com/webpack/contributors-guide/home) that spans beyond this single repo. We welcome you to check out any of the repositories in [our organization](https://github.com/webpack) or [webpack-contrib organization](https://github.com/webpack-contrib) which houses all of our loaders and plugins.
diff --git a/bin/webpack.js b/bin/webpack.js
index 26273bdbc75..ba71ec29ef6 100755
--- a/bin/webpack.js
+++ b/bin/webpack.js
@@ -16,11 +16,11 @@ const runCommand = (command, args) => {
shell: true
});
- executedCommand.on("error", error => {
+ executedCommand.on("error", (error) => {
reject(error);
});
- executedCommand.on("exit", code => {
+ executedCommand.on("exit", (code) => {
if (code === 0) {
resolve();
} else {
@@ -34,7 +34,7 @@ const runCommand = (command, args) => {
* @param {string} packageName name of the package
* @returns {boolean} is the package installed?
*/
-const isInstalled = packageName => {
+const isInstalled = (packageName) => {
if (process.versions.pnp) {
return true;
}
@@ -76,7 +76,7 @@ const isInstalled = packageName => {
* @param {CliOption} cli options
* @returns {void}
*/
-const runCli = cli => {
+const runCli = (cli) => {
const path = require("path");
const pkgPath = require.resolve(`${cli.package}/package.json`);
@@ -85,7 +85,7 @@ const runCli = cli => {
if (pkg.type === "module" || /\.mjs/i.test(pkg.bin[cli.binName])) {
import(path.resolve(path.dirname(pkgPath), pkg.bin[cli.binName])).catch(
- err => {
+ (err) => {
console.error(err);
process.exitCode = 1;
}
@@ -152,7 +152,7 @@ if (!cli.installed) {
// executed. Setting the exit code here to ensure the script exits correctly in those cases. The callback
// function is responsible for clearing the exit code if the user wishes to install webpack-cli.
process.exitCode = 1;
- questionInterface.question(question, answer => {
+ questionInterface.question(question, (answer) => {
questionInterface.close();
const normalizedAnswer = answer.toLowerCase().startsWith("y");
@@ -183,7 +183,7 @@ if (!cli.installed) {
.then(() => {
runCli(cli);
})
- .catch(err => {
+ .catch((err) => {
console.error(err);
process.exitCode = 1;
});
diff --git a/declarations/WebpackOptions.d.ts b/declarations/WebpackOptions.d.ts
index e2ba028309a..c6116554e4a 100644
--- a/declarations/WebpackOptions.d.ts
+++ b/declarations/WebpackOptions.d.ts
@@ -3287,6 +3287,10 @@ export interface JavascriptParserOptions {
* Enable/disable parsing "import { createRequire } from "module"" and evaluating createRequire().
*/
createRequire?: boolean | string;
+ /**
+ * Enable experimental tc39 proposal https://github.com/tc39/proposal-defer-import-eval. This allows to defer execution of a module until it's first use.
+ */
+ deferImport?: boolean;
/**
* Specifies global fetchPriority for dynamic import.
*/
diff --git a/eslint.config.mjs b/eslint.config.mjs
index 0cdd3278e53..a2fe9268c28 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -137,9 +137,6 @@ export default defineConfig([
"id-length": "off",
- "unicorn/no-array-for-each": "off",
- "unicorn/prefer-includes": "off",
-
"jsdoc/require-jsdoc": "off",
// Revisit it in future
@@ -151,9 +148,6 @@ export default defineConfig([
{
files: ["test/**/*.js"],
rules: {
- // TODO enable me
- strict: "off",
-
// Some our tests contain `package.json` without `engines`, but tests should work on Node.js@10, so let's disable it
"n/prefer-node-protocol": "off",
@@ -208,7 +202,6 @@ export default defineConfig([
{
files: [
"test/configCases/{dll-plugin-entry,dll-plugin-side-effects,dll-plugin}/**/webpack.config.js",
- "examples/**/*.js",
"test/NodeTemplatePlugin.test.js",
"test/PersistentCaching.test.js"
],
diff --git a/examples/module-code-splitting/README.md b/examples/module-code-splitting/README.md
index 36ad2da8154..5ea18941e70 100644
--- a/examples/module-code-splitting/README.md
+++ b/examples/module-code-splitting/README.md
@@ -145,22 +145,22 @@ export function reset() {
/******/ };
/******/
/******/ var installChunk = (data) => {
-/******/ var {__webpack_ids__, __webpack_modules__, __webpack_runtime__} = data;
+/******/ var {__webpack_esm_ids__, __webpack_esm_modules__, __webpack_esm_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 __webpack_modules__) {
-/******/ if(__webpack_require__.o(__webpack_modules__, moduleId)) {
-/******/ __webpack_require__.m[moduleId] = __webpack_modules__[moduleId];
+/******/ for(moduleId in __webpack_esm_modules__) {
+/******/ if(__webpack_require__.o(__webpack_esm_modules__, moduleId)) {
+/******/ __webpack_require__.m[moduleId] = __webpack_esm_modules__[moduleId];
/******/ }
/******/ }
-/******/ if(__webpack_runtime__) __webpack_runtime__(__webpack_require__);
-/******/ for(;i < __webpack_ids__.length; i++) {
-/******/ chunkId = __webpack_ids__[i];
+/******/ if(__webpack_esm_runtime__) __webpack_esm_runtime__(__webpack_require__);
+/******/ for(;i < __webpack_esm_ids__.length; i++) {
+/******/ chunkId = __webpack_esm_ids__[i];
/******/ if(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {
/******/ installedChunks[chunkId][0]();
/******/ }
-/******/ installedChunks[__webpack_ids__[i]] = 0;
+/******/ installedChunks[__webpack_esm_ids__[i]] = 0;
/******/ }
/******/
/******/ }
@@ -237,7 +237,7 @@ setTimeout(async () => {
# dist/output.js (production)
```javascript
-var e,t,o={},r={};function n(e){var t=r[e];if(void 0!==t)return t.exports;var i=r[e]={exports:{}};return o[e](i,i.exports,n),i.exports}n.m=o,n.d=(e,t)=>{for(var o in t)n.o(t,o)&&!n.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:t[o]})},n.f={},n.e=e=>Promise.all(Object.keys(n.f).reduce((t,o)=>(n.f[o](e,t),t),[])),n.u=e=>e+".output.js",n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.p="dist/",e={792:0},t=t=>{var o,r,{__webpack_ids__:i,__webpack_modules__:a,__webpack_runtime__:s}=t,u=0;for(o in a)n.o(a,o)&&(n.m[o]=a[o]);for(s&&s(n);u{var i=n.o(e,o)?e[o]:void 0;if(0!==i)if(i)r.push(i[1]);else{var a=import(n.p+n.u(o)).then(t,t=>{throw 0!==e[o]&&(e[o]=void 0),t});a=Promise.race([a,new Promise(t=>i=e[o]=[t])]),r.push(i[1]=a)}};const i=e=>console.log(e);setTimeout(async()=>{const e=await n.e(481).then(n.bind(n,481));i(e.value),e.increment(),e.increment(),e.increment(),i(e.value),await(async()=>{(await n.e(481).then(n.bind(n,481))).reset()})(),i(e.value)},100);
+var e,t,o={},r={};function n(e){var t=r[e];if(void 0!==t)return t.exports;var i=r[e]={exports:{}};return o[e](i,i.exports,n),i.exports}n.m=o,n.d=(e,t)=>{for(var o in t)n.o(t,o)&&!n.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:t[o]})},n.f={},n.e=e=>Promise.all(Object.keys(n.f).reduce((t,o)=>(n.f[o](e,t),t),[])),n.u=e=>e+".output.js",n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.p="dist/",e={792:0},t=t=>{var o,r,{__webpack_esm_ids__:i,__webpack_esm_modules__:a,__webpack_esm_runtime__:s}=t,u=0;for(o in a)n.o(a,o)&&(n.m[o]=a[o]);for(s&&s(n);u{var i=n.o(e,o)?e[o]:void 0;if(0!==i)if(i)r.push(i[1]);else{var a=import(n.p+n.u(o)).then(t,t=>{throw 0!==e[o]&&(e[o]=void 0),t});a=Promise.race([a,new Promise(t=>i=e[o]=[t])]),r.push(i[1]=a)}};const i=e=>console.log(e);setTimeout(async()=>{const e=await n.e(481).then(n.bind(n,481));i(e.value),e.increment(),e.increment(),e.increment(),i(e.value),await(async()=>{(await n.e(481).then(n.bind(n,481))).reset()})(),i(e.value)},100);
```
# Info
@@ -245,11 +245,11 @@ var e,t,o={},r={};function n(e){var t=r[e];if(void 0!==t)return t.exports;var i=
## Unoptimized
```
-asset output.js 6.66 KiB [emitted] [javascript module] (name: main)
-asset 1.output.js 1.38 KiB [emitted] [javascript module]
-chunk (runtime: main) output.js (main) 420 bytes (javascript) 3.07 KiB (runtime) [entry] [rendered]
+asset output.js 6.71 KiB [emitted] [javascript module] (name: main)
+asset 1.output.js 1.39 KiB [emitted] [javascript module]
+chunk (runtime: main) output.js (main) 420 bytes (javascript) 3.11 KiB (runtime) [entry] [rendered]
> ./example.js main
- runtime modules 3.07 KiB 7 modules
+ runtime modules 3.11 KiB 7 modules
./example.js + 1 modules 420 bytes [built] [code generated]
[no exports]
[no exports used]
@@ -268,8 +268,8 @@ webpack X.X.X compiled successfully
## Production mode
```
-asset output.js 1.19 KiB [emitted] [javascript module] [minimized] (name: main)
-asset 481.output.js 249 bytes [emitted] [javascript module] [minimized]
+asset output.js 1.2 KiB [emitted] [javascript module] [minimized] (name: main)
+asset 481.output.js 261 bytes [emitted] [javascript module] [minimized]
chunk (runtime: main) 481.output.js 146 bytes [rendered]
> ./counter ./methods.js 2:8-27
> ./counter ./example.js 4:23-42
@@ -277,9 +277,9 @@ chunk (runtime: main) 481.output.js 146 bytes [rendered]
[exports: decrement, increment, reset, value]
import() ./counter ./example.js + 1 modules ./example.js 4:23-42
import() ./counter ./example.js + 1 modules ./methods.js 2:8-27
-chunk (runtime: main) output.js (main) 420 bytes (javascript) 3.07 KiB (runtime) [entry] [rendered]
+chunk (runtime: main) output.js (main) 420 bytes (javascript) 3.11 KiB (runtime) [entry] [rendered]
> ./example.js main
- runtime modules 3.07 KiB 7 modules
+ runtime modules 3.11 KiB 7 modules
./example.js + 1 modules 420 bytes [built] [code generated]
[no exports]
[no exports used]
diff --git a/examples/module-worker/README.md b/examples/module-worker/README.md
index 032e02deda8..fa0732fe87d 100644
--- a/examples/module-worker/README.md
+++ b/examples/module-worker/README.md
@@ -261,22 +261,22 @@ export const add = (content, from) => {
/******/ };
/******/
/******/ var installChunk = (data) => {
-/******/ var {__webpack_ids__, __webpack_modules__, __webpack_runtime__} = data;
+/******/ var {__webpack_esm_ids__, __webpack_esm_modules__, __webpack_esm_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 __webpack_modules__) {
-/******/ if(__webpack_require__.o(__webpack_modules__, moduleId)) {
-/******/ __webpack_require__.m[moduleId] = __webpack_modules__[moduleId];
+/******/ for(moduleId in __webpack_esm_modules__) {
+/******/ if(__webpack_require__.o(__webpack_esm_modules__, moduleId)) {
+/******/ __webpack_require__.m[moduleId] = __webpack_esm_modules__[moduleId];
/******/ }
/******/ }
-/******/ if(__webpack_runtime__) __webpack_runtime__(__webpack_require__);
-/******/ for(;i < __webpack_ids__.length; i++) {
-/******/ chunkId = __webpack_ids__[i];
+/******/ if(__webpack_esm_runtime__) __webpack_esm_runtime__(__webpack_require__);
+/******/ for(;i < __webpack_esm_ids__.length; i++) {
+/******/ chunkId = __webpack_esm_ids__[i];
/******/ if(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {
/******/ installedChunks[chunkId][0]();
/******/ }
-/******/ installedChunks[__webpack_ids__[i]] = 0;
+/******/ installedChunks[__webpack_esm_ids__[i]] = 0;
/******/ }
/******/
/******/ }
@@ -531,22 +531,22 @@ fibWorker.onmessage = event => {
/******/ };
/******/
/******/ var installChunk = (data) => {
-/******/ var {__webpack_ids__, __webpack_modules__, __webpack_runtime__} = data;
+/******/ var {__webpack_esm_ids__, __webpack_esm_modules__, __webpack_esm_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 __webpack_modules__) {
-/******/ if(__webpack_require__.o(__webpack_modules__, moduleId)) {
-/******/ __webpack_require__.m[moduleId] = __webpack_modules__[moduleId];
+/******/ for(moduleId in __webpack_esm_modules__) {
+/******/ if(__webpack_require__.o(__webpack_esm_modules__, moduleId)) {
+/******/ __webpack_require__.m[moduleId] = __webpack_esm_modules__[moduleId];
/******/ }
/******/ }
-/******/ if(__webpack_runtime__) __webpack_runtime__(__webpack_require__);
-/******/ for(;i < __webpack_ids__.length; i++) {
-/******/ chunkId = __webpack_ids__[i];
+/******/ if(__webpack_esm_runtime__) __webpack_esm_runtime__(__webpack_require__);
+/******/ for(;i < __webpack_esm_ids__.length; i++) {
+/******/ chunkId = __webpack_esm_ids__[i];
/******/ if(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {
/******/ installedChunks[chunkId][0]();
/******/ }
-/******/ installedChunks[__webpack_ids__[i]] = 0;
+/******/ installedChunks[__webpack_esm_ids__[i]] = 0;
/******/ }
/******/
/******/ }
@@ -620,7 +620,7 @@ onconnect = function (e) {
```
```javascript
-var e,o,t={},r={};function s(e){var o=r[e];if(void 0!==o)return o.exports;var n=r[e]={exports:{}};return t[e](n,n.exports,s),n.exports}s.m=t,s.d=(e,o)=>{for(var t in o)s.o(o,t)&&!s.o(e,t)&&Object.defineProperty(e,t,{enumerable:!0,get:o[t]})},s.f={},s.e=e=>Promise.all(Object.keys(s.f).reduce((o,t)=>(s.f[t](e,o),o),[])),s.u=e=>e+".js",s.o=(e,o)=>Object.prototype.hasOwnProperty.call(e,o),s.p="/dist/",e={377:0},o=o=>{var t,r,{__webpack_ids__:n,__webpack_modules__:a,__webpack_runtime__:i}=o,c=0;for(t in a)s.o(a,t)&&(s.m[t]=a[t]);for(i&&i(s);c{var n=s.o(e,t)?e[t]:void 0;if(0!==n)if(n)r.push(n[1]);else{var a=import(s.p+s.u(t)).then(o,o=>{throw 0!==e[t]&&(e[t]=void 0),o});a=Promise.race([a,new Promise(o=>n=e[t]=[o])]),r.push(n[1]=a)}},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 s.e(936).then(s.bind(s,936));e(t.content,t.from);case"history":const{history:r}=await s.e(936).then(s.bind(s,936));o.postMessage({type:"history",history:r})}}};
+var e,o,t={},r={};function s(e){var o=r[e];if(void 0!==o)return o.exports;var n=r[e]={exports:{}};return t[e](n,n.exports,s),n.exports}s.m=t,s.d=(e,o)=>{for(var t in o)s.o(o,t)&&!s.o(e,t)&&Object.defineProperty(e,t,{enumerable:!0,get:o[t]})},s.f={},s.e=e=>Promise.all(Object.keys(s.f).reduce((o,t)=>(s.f[t](e,o),o),[])),s.u=e=>e+".js",s.o=(e,o)=>Object.prototype.hasOwnProperty.call(e,o),s.p="/dist/",e={377:0},o=o=>{var t,r,{__webpack_esm_ids__:n,__webpack_esm_modules__:a,__webpack_esm_runtime__:i}=o,c=0;for(t in a)s.o(a,t)&&(s.m[t]=a[t]);for(i&&i(s);c{var n=s.o(e,t)?e[t]:void 0;if(0!==n)if(n)r.push(n[1]);else{var a=import(s.p+s.u(t)).then(o,o=>{throw 0!==e[t]&&(e[t]=void 0),o});a=Promise.race([a,new Promise(o=>n=e[t]=[o])]),r.push(n[1]=a)}},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 s.e(936).then(s.bind(s,936));e(t.content,t.from);case"history":const{history:r}=await s.e(936).then(s.bind(s,936));o.postMessage({type:"history",history:r})}}};
```
# dist/workers/fibonacci.js
@@ -728,22 +728,22 @@ var e,o,t={},r={};function s(e){var o=r[e];if(void 0!==o)return o.exports;var n=
/******/ };
/******/
/******/ var installChunk = (data) => {
-/******/ var {__webpack_ids__, __webpack_modules__, __webpack_runtime__} = data;
+/******/ var {__webpack_esm_ids__, __webpack_esm_modules__, __webpack_esm_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 __webpack_modules__) {
-/******/ if(__webpack_require__.o(__webpack_modules__, moduleId)) {
-/******/ __webpack_require__.m[moduleId] = __webpack_modules__[moduleId];
+/******/ for(moduleId in __webpack_esm_modules__) {
+/******/ if(__webpack_require__.o(__webpack_esm_modules__, moduleId)) {
+/******/ __webpack_require__.m[moduleId] = __webpack_esm_modules__[moduleId];
/******/ }
/******/ }
-/******/ if(__webpack_runtime__) __webpack_runtime__(__webpack_require__);
-/******/ for(;i < __webpack_ids__.length; i++) {
-/******/ chunkId = __webpack_ids__[i];
+/******/ if(__webpack_esm_runtime__) __webpack_esm_runtime__(__webpack_require__);
+/******/ for(;i < __webpack_esm_ids__.length; i++) {
+/******/ chunkId = __webpack_esm_ids__[i];
/******/ if(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {
/******/ installedChunks[chunkId][0]();
/******/ }
-/******/ installedChunks[__webpack_ids__[i]] = 0;
+/******/ installedChunks[__webpack_esm_ids__[i]] = 0;
/******/ }
/******/
/******/ }
@@ -802,15 +802,15 @@ onmessage = async event => {
```
```javascript
-var e,r,o={},t={};function a(e){var r=t[e];if(void 0!==r)return r.exports;var s=t[e]={exports:{}};return o[e](s,s.exports,a),s.exports}a.m=o,a.d=(e,r)=>{for(var o in r)a.o(r,o)&&!a.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:r[o]})},a.f={},a.e=e=>Promise.all(Object.keys(a.f).reduce((r,o)=>(a.f[o](e,r),r),[])),a.u=e=>e+".js",a.o=(e,r)=>Object.prototype.hasOwnProperty.call(e,r),a.p="/dist/",e={721:0},r=r=>{var o,t,{__webpack_ids__:s,__webpack_modules__:i,__webpack_runtime__:n}=r,p=0;for(o in i)a.o(i,o)&&(a.m[o]=i[o]);for(n&&n(a);p{var s=a.o(e,o)?e[o]:void 0;if(0!==s)if(s)t.push(s[1]);else{var i=import(a.p+a.u(o)).then(r,r=>{throw 0!==e[o]&&(e[o]=void 0),r});i=Promise.race([i,new Promise(r=>s=e[o]=[r])]),t.push(s[1]=i)}},onmessage=async e=>{const{fibonacci:r}=await a.e(129).then(a.bind(a,129)),o=JSON.parse(e.data);postMessage(`fib(${o}) = ${r(o)}`)};
+var e,r,o={},s={};function t(e){var r=s[e];if(void 0!==r)return r.exports;var a=s[e]={exports:{}};return o[e](a,a.exports,t),a.exports}t.m=o,t.d=(e,r)=>{for(var o in r)t.o(r,o)&&!t.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:r[o]})},t.f={},t.e=e=>Promise.all(Object.keys(t.f).reduce((r,o)=>(t.f[o](e,r),r),[])),t.u=e=>e+".js",t.o=(e,r)=>Object.prototype.hasOwnProperty.call(e,r),t.p="/dist/",e={721:0},r=r=>{var o,s,{__webpack_esm_ids__:a,__webpack_esm_modules__:i,__webpack_esm_runtime__:n}=r,p=0;for(o in i)t.o(i,o)&&(t.m[o]=i[o]);for(n&&n(t);p{var a=t.o(e,o)?e[o]:void 0;if(0!==a)if(a)s.push(a[1]);else{var i=import(t.p+t.u(o)).then(r,r=>{throw 0!==e[o]&&(e[o]=void 0),r});i=Promise.race([i,new Promise(r=>a=e[o]=[r])]),s.push(a[1]=i)}},onmessage=async e=>{const{fibonacci:r}=await t.e(129).then(t.bind(t,129)),o=JSON.parse(e.data);postMessage(`fib(${o}) = ${r(o)}`)};
```
# dist/129.js
```javascript
-export const __webpack_id__ = 129;
-export const __webpack_ids__ = [129];
-export const __webpack_modules__ = {
+export const __webpack_esm_id__ = 129;
+export const __webpack_esm_ids__ = [129];
+export const __webpack_esm_modules__ = {
/***/ 3:
/*!**********************!*\
@@ -841,11 +841,11 @@ function fibonacci(n) {
## Unoptimized
```
-asset main.js 8.79 KiB [emitted] [javascript module] (name: main)
-asset chat.js 6.7 KiB [emitted] [javascript module] (name: chat)
-asset workers/fibonacci.js 6.35 KiB [emitted] [javascript module] (name: fibonacci)
-asset 936.js 1.04 KiB [emitted] [javascript module]
-asset 129.js 881 bytes [emitted] [javascript module]
+asset main.js 8.83 KiB [emitted] [javascript module] (name: main)
+asset chat.js 6.75 KiB [emitted] [javascript module] (name: chat)
+asset workers/fibonacci.js 6.39 KiB [emitted] [javascript module] (name: fibonacci)
+asset 936.js 1.05 KiB [emitted] [javascript module]
+asset 129.js 893 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
@@ -854,21 +854,21 @@ chunk (runtime: 9a81d90cfd0dfd13d748, main) 129.js 103 bytes [rendered]
[used exports unknown]
import() ./fibonacci ./example.js 70:30-51
import() ./fibonacci ./fib-worker.js 2:29-50
-chunk (runtime: 1fad8bf8de78b0a77bfd) chat.js (chat) 442 bytes (javascript) 3.06 KiB (runtime) [entry] [rendered]
+chunk (runtime: 1fad8bf8de78b0a77bfd) chat.js (chat) 442 bytes (javascript) 3.11 KiB (runtime) [entry] [rendered]
> ./example.js 25:19-31:1
- runtime modules 3.06 KiB 7 modules
+ runtime modules 3.11 KiB 7 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) 3.06 KiB (runtime) [entry] [rendered]
+chunk (runtime: 9a81d90cfd0dfd13d748) workers/fibonacci.js (fibonacci) 176 bytes (javascript) 3.11 KiB (runtime) [entry] [rendered]
> ./example.js 80:18-84:2
- runtime modules 3.06 KiB 7 modules
+ runtime modules 3.11 KiB 7 modules
./fib-worker.js 176 bytes [built] [code generated]
[used exports unknown]
new Worker() ./fib-worker.js ./example.js 80:18-84:2
-chunk (runtime: main) main.js (main) 2.25 KiB (javascript) 3.24 KiB (runtime) [entry] [rendered]
+chunk (runtime: main) main.js (main) 2.25 KiB (javascript) 3.28 KiB (runtime) [entry] [rendered]
> ./example.js main
- runtime modules 3.24 KiB 7 modules
+ runtime modules 3.28 KiB 7 modules
./example.js 2.25 KiB [built] [code generated]
[used exports unknown]
entry ./example.js main
@@ -886,11 +886,11 @@ webpack X.X.X compiled successfully
## Production mode
```
-asset main.js 2.35 KiB [emitted] [javascript module] [minimized] (name: main)
-asset chat.js 1.07 KiB [emitted] [javascript module] [minimized] (name: chat)
-asset workers/fibonacci.js 939 bytes [emitted] [javascript module] [minimized] (name: fibonacci)
-asset 936.js 216 bytes [emitted] [javascript module] [minimized]
-asset 129.js 190 bytes [emitted] [javascript module] [minimized]
+asset main.js 2.36 KiB [emitted] [javascript module] [minimized] (name: main)
+asset chat.js 1.08 KiB [emitted] [javascript module] [minimized] (name: chat)
+asset workers/fibonacci.js 951 bytes [emitted] [javascript module] [minimized] (name: fibonacci)
+asset 936.js 228 bytes [emitted] [javascript module] [minimized]
+asset 129.js 202 bytes [emitted] [javascript module] [minimized]
chunk (runtime: 9a81d90cfd0dfd13d748, main) 129.js 103 bytes [rendered]
> ./fibonacci ./fib-worker.js 2:29-50
> ./fibonacci ./example.js 70:30-51
@@ -899,21 +899,21 @@ chunk (runtime: 9a81d90cfd0dfd13d748, main) 129.js 103 bytes [rendered]
[all exports used]
import() ./fibonacci ./example.js 70:30-51
import() ./fibonacci ./fib-worker.js 2:29-50
-chunk (runtime: 1fad8bf8de78b0a77bfd) chat.js (chat) 442 bytes (javascript) 2.8 KiB (runtime) [entry] [rendered]
+chunk (runtime: 1fad8bf8de78b0a77bfd) chat.js (chat) 442 bytes (javascript) 2.84 KiB (runtime) [entry] [rendered]
> ./example.js 25:19-31:1
- runtime modules 2.8 KiB 6 modules
+ runtime modules 2.84 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.8 KiB (runtime) [entry] [rendered]
+chunk (runtime: 9a81d90cfd0dfd13d748) workers/fibonacci.js (fibonacci) 176 bytes (javascript) 2.84 KiB (runtime) [entry] [rendered]
> ./example.js 80:18-84:2
- runtime modules 2.8 KiB 6 modules
+ runtime modules 2.84 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
-chunk (runtime: main) main.js (main) 2.25 KiB (javascript) 2.97 KiB (runtime) [entry] [rendered]
+chunk (runtime: main) main.js (main) 2.25 KiB (javascript) 3.01 KiB (runtime) [entry] [rendered]
> ./example.js main
- runtime modules 2.97 KiB 6 modules
+ runtime modules 3.01 KiB 6 modules
./example.js 2.25 KiB [built] [code generated]
[no exports used]
entry ./example.js main
diff --git a/examples/nodejs-addons/README.md b/examples/nodejs-addons/README.md
index 12792394eba..1f159d50b12 100644
--- a/examples/nodejs-addons/README.md
+++ b/examples/nodejs-addons/README.md
@@ -65,10 +65,10 @@ webpack X.X.X compiled successfully
```
asset 7726cbf5eb6de9759226.node 16.5 KiB [emitted] [immutable] [from: file.node] (auxiliary name: main)
-asset output.js 510 bytes [emitted] [minimized] (name: main)
-chunk (runtime: main) output.js (main) 16.5 KiB (asset) 457 bytes (javascript) 440 bytes (runtime) [entry] [rendered]
+asset output.js 515 bytes [emitted] [minimized] (name: main)
+chunk (runtime: main) output.js (main) 16.5 KiB (asset) 457 bytes (javascript) 445 bytes (runtime) [entry] [rendered]
> ./example.js main
- runtime modules 440 bytes 3 modules
+ runtime modules 445 bytes 3 modules
dependent modules 16.5 KiB (asset) 42 bytes (javascript) [dependent] 1 module
./example.js + 2 modules 415 bytes [not cacheable] [built] [code generated]
[no exports]
diff --git a/generate-types-config.js b/generate-types-config.js
index a3ce7af1250..89205e3496b 100644
--- a/generate-types-config.js
+++ b/generate-types-config.js
@@ -4,7 +4,8 @@ module.exports = {
nameMapping: {
FsStats: /^Stats Import fs/,
validateFunction: /^validate Import/,
- Configuration: /^WebpackOptions /
+ Configuration: /^WebpackOptions /,
+ MultiConfiguration: /^MultiWebpackOptions /
},
exclude: [/^devServer in WebpackOptions /],
include: [/^(_module|_compilation|_compiler) in NormalModuleLoaderContext /]
diff --git a/lib/APIPlugin.js b/lib/APIPlugin.js
index b8978e337e8..56dcf63e0be 100644
--- a/lib/APIPlugin.js
+++ b/lib/APIPlugin.js
@@ -169,7 +169,7 @@ class APIPlugin {
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.chunkName)
- .tap(PLUGIN_NAME, chunk => {
+ .tap(PLUGIN_NAME, (chunk) => {
compilation.addRuntimeModule(
chunk,
new ChunkNameRuntimeModule(/** @type {string} */ (chunk.name))
@@ -190,13 +190,11 @@ class APIPlugin {
PLUGIN_NAME,
(source, module, renderContext) => {
if (/** @type {BuildInfo} */ (module.buildInfo).needCreateRequire) {
- const needPrefix =
- renderContext.runtimeTemplate.supportNodePrefixForCoreModules();
const chunkInitFragments = [
new InitFragment(
- `import { createRequire as __WEBPACK_EXTERNAL_createRequire } from "${
- needPrefix ? "node:" : ""
- }module";\n`,
+ `import { createRequire as __WEBPACK_EXTERNAL_createRequire } from ${renderContext.runtimeTemplate.renderNodePrefixForCoreModule(
+ "module"
+ )};\n`,
InitFragment.STAGE_HARMONY_IMPORTS,
0,
"external module node-commonjs"
@@ -213,10 +211,10 @@ class APIPlugin {
/**
* @param {JavascriptParser} parser the parser
*/
- const handler = parser => {
+ const handler = (parser) => {
for (const key of Object.keys(REPLACEMENTS)) {
const info = REPLACEMENTS[key];
- parser.hooks.expression.for(key).tap(PLUGIN_NAME, expression => {
+ parser.hooks.expression.for(key).tap(PLUGIN_NAME, (expression) => {
const dep = toConstantDependency(parser, info.expr, info.req);
if (key === "__non_webpack_require__" && this.options.module) {
@@ -227,7 +225,7 @@ class APIPlugin {
return dep(expression);
});
if (info.assign === false) {
- parser.hooks.assign.for(key).tap(PLUGIN_NAME, expr => {
+ parser.hooks.assign.for(key).tap(PLUGIN_NAME, (expr) => {
const err = new WebpackError(`${key} must not be assigned`);
err.loc = /** @type {DependencyLocation} */ (expr.loc);
throw err;
@@ -242,7 +240,7 @@ class APIPlugin {
parser.hooks.expression
.for("__webpack_layer__")
- .tap(PLUGIN_NAME, expr => {
+ .tap(PLUGIN_NAME, (expr) => {
const dep = new ConstDependency(
JSON.stringify(parser.state.module.layer),
/** @type {Range} */ (expr.range)
@@ -253,7 +251,7 @@ class APIPlugin {
});
parser.hooks.evaluateIdentifier
.for("__webpack_layer__")
- .tap(PLUGIN_NAME, expr =>
+ .tap(PLUGIN_NAME, (expr) =>
(parser.state.module.layer === null
? new BasicEvaluatedExpression().setNull()
: new BasicEvaluatedExpression().setString(
@@ -263,7 +261,7 @@ class APIPlugin {
);
parser.hooks.evaluateTypeof
.for("__webpack_layer__")
- .tap(PLUGIN_NAME, expr =>
+ .tap(PLUGIN_NAME, (expr) =>
new BasicEvaluatedExpression()
.setString(
parser.state.module.layer === null ? "object" : "string"
@@ -273,7 +271,7 @@ class APIPlugin {
parser.hooks.expression
.for("__webpack_module__.id")
- .tap(PLUGIN_NAME, expr => {
+ .tap(PLUGIN_NAME, (expr) => {
/** @type {BuildInfo} */
(parser.state.module.buildInfo).moduleConcatenationBailout =
"__webpack_module__.id";
@@ -289,7 +287,7 @@ class APIPlugin {
parser.hooks.expression
.for("__webpack_module__")
- .tap(PLUGIN_NAME, expr => {
+ .tap(PLUGIN_NAME, (expr) => {
/** @type {BuildInfo} */
(parser.state.module.buildInfo).moduleConcatenationBailout =
"__webpack_module__";
diff --git a/lib/AutomaticPrefetchPlugin.js b/lib/AutomaticPrefetchPlugin.js
index b0926614e69..1295f8245ef 100644
--- a/lib/AutomaticPrefetchPlugin.js
+++ b/lib/AutomaticPrefetchPlugin.js
@@ -31,7 +31,7 @@ class AutomaticPrefetchPlugin {
);
/** @type {{context: string | null, request: string}[] | null} */
let lastModules = null;
- compiler.hooks.afterCompile.tap(PLUGIN_NAME, compilation => {
+ compiler.hooks.afterCompile.tap(PLUGIN_NAME, (compilation) => {
lastModules = [];
for (const m of compilation.modules) {
@@ -54,7 +54,7 @@ class AutomaticPrefetchPlugin {
callback
);
},
- err => {
+ (err) => {
lastModules = null;
callback(err);
}
diff --git a/lib/BannerPlugin.js b/lib/BannerPlugin.js
index 22ec021f6b9..b45256e4fad 100644
--- a/lib/BannerPlugin.js
+++ b/lib/BannerPlugin.js
@@ -32,7 +32,7 @@ const validate = createSchemaValidation(
* @param {string} str string to wrap
* @returns {string} wrapped string
*/
-const wrapComment = str => {
+const wrapComment = (str) => {
if (!str.includes("\n")) {
return Template.toComment(str);
}
@@ -67,7 +67,7 @@ class BannerPlugin {
/** @type {BannerFunction} */
this.banner = this.options.raw
? getBanner
- : /** @type {BannerFunction} */ data => wrapComment(getBanner(data));
+ : /** @type {BannerFunction} */ (data) => wrapComment(getBanner(data));
} else {
const banner = this.options.raw
? bannerOption
@@ -93,7 +93,7 @@ class BannerPlugin {
const stage =
this.options.stage || Compilation.PROCESS_ASSETS_STAGE_ADDITIONS;
- compiler.hooks.compilation.tap(PLUGIN_NAME, compilation => {
+ compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
compilation.hooks.processAssets.tap({ name: PLUGIN_NAME, stage }, () => {
for (const chunk of compilation.chunks) {
if (options.entryOnly && !chunk.canBeInitial()) {
@@ -114,7 +114,7 @@ class BannerPlugin {
data
);
- compilation.updateAsset(file, old => {
+ compilation.updateAsset(file, (old) => {
const cached = cache.get(old);
if (!cached || cached.comment !== comment) {
const source = options.footer
diff --git a/lib/Cache.js b/lib/Cache.js
index 757119c9de5..f807055e956 100644
--- a/lib/Cache.js
+++ b/lib/Cache.js
@@ -40,7 +40,7 @@ const {
* @param {(err?: Error) => void} callback callback
* @returns {(err?: Error) => void} callback
*/
-const needCalls = (times, callback) => err => {
+const needCalls = (times, callback) => (err) => {
if (--times === 0) {
return callback(err);
}
diff --git a/lib/CacheFacade.js b/lib/CacheFacade.js
index 190de11dc06..8887d3d955e 100644
--- a/lib/CacheFacade.js
+++ b/lib/CacheFacade.js
@@ -61,8 +61,8 @@ class MultiItemCache {
* @param {number} i index
* @returns {Promise} promise with the data
*/
- const next = i =>
- this._items[i].getPromise().then(result => {
+ const next = (i) =>
+ this._items[i].getPromise().then((result) => {
if (result !== undefined) return result;
if (++i < this._items.length) return next(i);
});
@@ -89,7 +89,7 @@ class MultiItemCache {
* @returns {Promise} promise signals when the value is stored
*/
storePromise(data) {
- return Promise.all(this._items.map(item => item.storePromise(data))).then(
+ return Promise.all(this._items.map((item) => item.storePromise(data))).then(
() => {}
);
}
@@ -149,7 +149,7 @@ class ItemCacheFacade {
*/
storePromise(data) {
return new Promise((resolve, reject) => {
- this._cache.store(this._name, this._etag, data, err => {
+ this._cache.store(this._name, this._etag, data, (err) => {
if (err) {
reject(err);
} else {
@@ -171,7 +171,7 @@ class ItemCacheFacade {
if (cacheEntry !== undefined) return cacheEntry;
computer((err, result) => {
if (err) return callback(err);
- this.store(result, err => {
+ this.store(result, (err) => {
if (err) return callback(err);
callback(null, result);
});
@@ -297,7 +297,7 @@ class CacheFacade {
*/
storePromise(identifier, etag, data) {
return new Promise((resolve, reject) => {
- this._cache.store(`${this._name}|${identifier}`, etag, data, err => {
+ this._cache.store(`${this._name}|${identifier}`, etag, data, (err) => {
if (err) {
reject(err);
} else {
@@ -321,7 +321,7 @@ class CacheFacade {
if (cacheEntry !== undefined) return cacheEntry;
computer((err, result) => {
if (err) return callback(err);
- this.store(identifier, etag, result, err => {
+ this.store(identifier, etag, result, (err) => {
if (err) return callback(err);
callback(null, result);
});
diff --git a/lib/CaseSensitiveModulesWarning.js b/lib/CaseSensitiveModulesWarning.js
index 2680753fa1b..0ee17aa56c6 100644
--- a/lib/CaseSensitiveModulesWarning.js
+++ b/lib/CaseSensitiveModulesWarning.js
@@ -14,7 +14,7 @@ const WebpackError = require("./WebpackError");
* @param {Module[]} modules the modules to be sorted
* @returns {Module[]} sorted version of original modules
*/
-const sortModules = modules =>
+const sortModules = (modules) =>
modules.sort((a, b) => {
const aIdent = a.identifier();
const bIdent = b.identifier();
@@ -33,7 +33,7 @@ const sortModules = modules =>
*/
const createModulesListMessage = (modules, moduleGraph) =>
modules
- .map(m => {
+ .map((m) => {
let message = `* ${m.identifier()}`;
const validReasons = [
...moduleGraph.getIncomingConnectionsByOriginModule(m).keys()
diff --git a/lib/Chunk.js b/lib/Chunk.js
index b19d06b6b9d..21fdaba9be7 100644
--- a/lib/Chunk.js
+++ b/lib/Chunk.js
@@ -583,7 +583,7 @@ class Chunk {
const chunks = new Set();
const initialChunks = intersect(
- Array.from(this.groupsIterable, g => new Set(g.chunks))
+ Array.from(this.groupsIterable, (g) => new Set(g.chunks))
);
const initialQueue = new Set(this.groupsIterable);
@@ -672,7 +672,7 @@ class Chunk {
const queue = new Set();
const initialChunks = intersect(
- Array.from(this.groupsIterable, g => new Set(g.chunks))
+ Array.from(this.groupsIterable, (g) => new Set(g.chunks))
);
for (const chunkGroup of this.groupsIterable) {
@@ -812,7 +812,7 @@ class Chunk {
* @param {Chunk} chunk a chunk
* @returns {void}
*/
- const addChildIdsByOrdersToMap = chunk => {
+ const addChildIdsByOrdersToMap = (chunk) => {
const data = chunk.getChildIdsByOrders(chunkGraph, filterFn);
for (const key of Object.keys(data)) {
let chunkMap = chunkMaps[key];
diff --git a/lib/ChunkGraph.js b/lib/ChunkGraph.js
index 0998125b286..f30cfb13d7e 100644
--- a/lib/ChunkGraph.js
+++ b/lib/ChunkGraph.js
@@ -76,13 +76,13 @@ class ModuleHashInfo {
* @param {SortableSet} set the set
* @returns {T[]} set as array
*/
-const getArray = set => [...set];
+const getArray = (set) => [...set];
/**
* @param {SortableSet} chunks the chunks
* @returns {RuntimeSpecSet} runtimes
*/
-const getModuleRuntimes = chunks => {
+const getModuleRuntimes = (chunks) => {
const runtimes = new RuntimeSpecSet();
for (const chunk of chunks) {
runtimes.add(chunk.runtime);
@@ -94,7 +94,7 @@ const getModuleRuntimes = chunks => {
* @param {WeakMap> | undefined} sourceTypesByModule sourceTypesByModule
* @returns {(set: SortableSet) => Map>} modules by source type
*/
-const modulesBySourceType = sourceTypesByModule => set => {
+const modulesBySourceType = (sourceTypesByModule) => (set) => {
/** @type {Map>} */
const map = new Map();
for (const module of set) {
@@ -136,10 +136,10 @@ const createOrderedArrayFunctionMap = new WeakMap();
* @param {ModuleComparator} comparator comparator function
* @returns {ModuleSetToArrayFunction} set as ordered array
*/
-const createOrderedArrayFunction = comparator => {
+const createOrderedArrayFunction = (comparator) => {
let fn = createOrderedArrayFunctionMap.get(comparator);
if (fn !== undefined) return fn;
- fn = set => {
+ fn = (set) => {
set.sortWith(comparator);
return [...set];
};
@@ -151,7 +151,7 @@ const createOrderedArrayFunction = comparator => {
* @param {Iterable} modules the modules to get the count/size of
* @returns {number} the size of the modules
*/
-const getModulesSize = modules => {
+const getModulesSize = (modules) => {
let size = 0;
for (const module of modules) {
for (const type of module.getSourceTypes()) {
@@ -165,7 +165,7 @@ const getModulesSize = modules => {
* @param {Iterable} modules the sortable Set to get the size of
* @returns {Record} the sizes of the modules
*/
-const getModulesSizes = modules => {
+const getModulesSizes = (modules) => {
const sizes = Object.create(null);
for (const module of modules) {
for (const type of module.getSourceTypes()) {
@@ -311,13 +311,13 @@ class ChunkGraph {
_getGraphRoots(set) {
const { moduleGraph } = this;
return [
- ...findGraphRoots(set, module => {
+ ...findGraphRoots(set, (module) => {
/** @type {Set} */
const set = new Set();
/**
* @param {Module} module module
*/
- const addDependencies = module => {
+ const addDependencies = (module) => {
for (const connection of moduleGraph.getOutgoingConnections(module)) {
if (!connection.module) continue;
const activeState = connection.getActiveState(undefined);
@@ -1272,7 +1272,10 @@ class ChunkGraph {
const array = [...cgc.runtimeModules];
array.sort(
concatComparators(
- compareSelect(r => /** @type {RuntimeModule} */ (r).stage, compareIds),
+ compareSelect(
+ (r) => /** @type {RuntimeModule} */ (r).stage,
+ compareIds
+ ),
compareModulesByIdentifier
)
);
@@ -1401,7 +1404,7 @@ class ChunkGraph {
throw new Error(
`No unique hash info entry for unspecified runtime for ${module.identifier()} (existing runtimes: ${Array.from(
hashes.keys(),
- r => runtimeToString(r)
+ (r) => runtimeToString(r)
).join(", ")}).
Caller might not support runtime-dependent code generation (opt-out via optimization.usedExports: "global").`
);
@@ -1493,7 +1496,7 @@ Caller might not support runtime-dependent code generation (opt-out via optimiza
cgm.runtimeRequirements = map;
return;
}
- runtimeRequirementsMap.update(runtime, runtimeRequirements => {
+ runtimeRequirementsMap.update(runtime, (runtimeRequirements) => {
if (runtimeRequirements === undefined) {
return transferOwnership ? items : new Set(items);
} else if (!transferOwnership || runtimeRequirements.size >= items.size) {
@@ -1623,7 +1626,7 @@ Caller might not support runtime-dependent code generation (opt-out via optimiza
* @param {ConnectionState} state state
* @returns {"F" | "T" | "O"} result
*/
- const activeStateToString = state => {
+ const activeStateToString = (state) => {
if (state === false) return "F";
if (state === true) return "T";
if (state === ModuleGraphConnection.TRANSITIVE_ONLY) return "O";
@@ -1675,7 +1678,7 @@ Caller might not support runtime-dependent code generation (opt-out via optimiza
let stateInfo = "";
forEachRuntime(
runtime,
- runtime => {
+ (runtime) => {
const state = connection.getActiveState(runtime);
states.add(state);
stateInfo += activeStateToString(state) + runtime;
@@ -1702,7 +1705,7 @@ Caller might not support runtime-dependent code generation (opt-out via optimiza
/**
* @param {Module} module module
*/
- const addModuleToHash = module => {
+ const addModuleToHash = (module) => {
hash.update(
this._getModuleGraphHashBigInt(
this._getChunkGraphModule(module),
@@ -1714,7 +1717,7 @@ Caller might not support runtime-dependent code generation (opt-out via optimiza
/**
* @param {Set} modules modules
*/
- const addModulesToHash = modules => {
+ const addModulesToHash = (modules) => {
let xor = ZERO_BIG_INT;
for (const m of modules) {
xor ^= this._getModuleGraphHashBigInt(
@@ -1769,7 +1772,7 @@ Caller might not support runtime-dependent code generation (opt-out via optimiza
* @param {Module} module the module
* @returns {ChunkGraph} the chunk graph
*/
- module => {
+ (module) => {
const chunkGraph = chunkGraphForModuleMap.get(module);
if (!chunkGraph) {
throw new Error(
@@ -1821,7 +1824,7 @@ Caller might not support runtime-dependent code generation (opt-out via optimiza
* @param {Chunk} chunk the chunk
* @returns {ChunkGraph} the chunk graph
*/
- chunk => {
+ (chunk) => {
const chunkGraph = chunkGraphForChunkMap.get(chunk);
if (!chunkGraph) {
throw new Error(
diff --git a/lib/ChunkGroup.js b/lib/ChunkGroup.js
index 5306625a6bc..36d7389d2fe 100644
--- a/lib/ChunkGroup.js
+++ b/lib/ChunkGroup.js
@@ -40,7 +40,7 @@ let debugId = 5000;
* @param {SortableSet} set set to convert to array.
* @returns {T[]} the array format of existing set
*/
-const getArray = set => [...set];
+const getArray = (set) => [...set];
/**
* A convenience method used to sort chunks based on their id's
@@ -165,7 +165,7 @@ class ChunkGroup {
* @returns {string} a unique concatenation of chunk debugId's
*/
get debugId() {
- return Array.from(this.chunks, x => x.debugId).join("+");
+ return Array.from(this.chunks, (x) => x.debugId).join("+");
}
/**
@@ -173,7 +173,7 @@ class ChunkGroup {
* @returns {string} a unique concatenation of chunk ids
*/
get id() {
- return Array.from(this.chunks, x => x.id).join("+");
+ return Array.from(this.chunks, (x) => x.id).join("+");
}
/**
@@ -533,7 +533,7 @@ class ChunkGroup {
if (cmp !== 0) return cmp;
return a.group.compareTo(chunkGraph, b.group);
});
- result[name] = list.map(i => i.group);
+ result[name] = list.map((i) => i.group);
}
return result;
}
diff --git a/lib/CleanPlugin.js b/lib/CleanPlugin.js
index cdc39201035..5a43a7dc32f 100644
--- a/lib/CleanPlugin.js
+++ b/lib/CleanPlugin.js
@@ -72,7 +72,7 @@ function getDirectories(assets) {
/**
* @param {string} filename asset filename
*/
- const addDirectory = filename => {
+ const addDirectory = (filename) => {
directories.add(path.dirname(filename));
};
@@ -87,38 +87,6 @@ function getDirectories(assets) {
return directories;
}
-/**
- * @param {string} a First directory path to compare
- * @param {string} b Second directory path to compare
- * @returns {boolean} True if both paths have the same parent directory
- */
-function isEqualPath(a, b) {
- return path.normalize(a) === path.normalize(b);
-}
-
-/**
- * @param {Map|Set} files Collection of files to check against
- * @param {string} file File path to check
- * @returns {boolean} True if the file or its parent exists in the collection
- */
-function hasFile(files, file) {
- if (files instanceof Set) {
- for (const dir of files) {
- if (isEqualPath(dir, file)) {
- return true;
- }
- }
- }
- if (files instanceof Map) {
- for (const dir of files.keys()) {
- if (isEqualPath(dir, file)) {
- return true;
- }
- }
- }
- return false;
-}
-
/** @typedef {Set} Diff */
/**
@@ -147,18 +115,18 @@ const getDiffToFs = (fs, outputPath, currentAssets, callback) => {
}
for (const entry of /** @type {string[]} */ (entries)) {
const file = entry;
- const filename = directory ? `${directory}/${file}` : file;
- if (
- !hasFile(directories, filename) &&
- !hasFile(currentAssets, filename)
- ) {
+ // Since path.normalize("./file") === path.normalize("file"),
+ // return file directly when directory === "."
+ const filename =
+ directory && directory !== "." ? `${directory}/${file}` : file;
+ if (!directories.has(filename) && !currentAssets.has(filename)) {
diff.add(filename);
}
}
callback();
});
},
- err => {
+ (err) => {
if (err) return callback(err);
callback(null, diff);
@@ -210,7 +178,7 @@ const applyDiff = (fs, outputPath, dry, logger, diff, isKept, callback) => {
/**
* @param {string} msg message
*/
- const log = msg => {
+ const log = (msg) => {
if (dry) {
logger.info(msg);
} else {
@@ -219,7 +187,7 @@ const applyDiff = (fs, outputPath, dry, logger, diff, isKept, callback) => {
};
/** @typedef {{ type: "check" | "unlink" | "rmdir", filename: string, parent: { remaining: number, job: Job } | undefined }} Job */
/** @type {Job[]} */
- const jobs = Array.from(diff.keys(), filename => ({
+ const jobs = Array.from(diff.keys(), (filename) => ({
type: "check",
filename,
parent: undefined
@@ -235,15 +203,15 @@ const applyDiff = (fs, outputPath, dry, logger, diff, isKept, callback) => {
* @param {Error & { code?: string }} err error
* @returns {void}
*/
- const handleError = err => {
+ const handleError = (err) => {
const isAlreadyRemoved = () =>
- new Promise(resolve => {
+ new Promise((resolve) => {
if (err.code === "ENOENT") {
resolve(true);
} else if (err.code === "EPERM") {
// https://github.com/isaacs/rimraf/blob/main/src/fix-eperm.ts#L37
// fs.existsSync(path) === false https://github.com/webpack/webpack/actions/runs/15493412975/job/43624272783?pr=19586
- doStat(fs, path, err => {
+ doStat(fs, path, (err) => {
if (err) {
resolve(err.code === "ENOENT");
} else {
@@ -255,7 +223,7 @@ const applyDiff = (fs, outputPath, dry, logger, diff, isKept, callback) => {
}
});
- isAlreadyRemoved().then(isRemoved => {
+ isAlreadyRemoved().then((isRemoved) => {
if (isRemoved) {
log(`${filename} was removed during cleaning by something else`);
handleParent();
@@ -334,7 +302,7 @@ const applyDiff = (fs, outputPath, dry, logger, diff, isKept, callback) => {
);
return process.nextTick(callback);
}
- fs.rmdir(path, err => {
+ fs.rmdir(path, (err) => {
if (err) return handleError(err);
handleParent();
callback();
@@ -352,7 +320,7 @@ const applyDiff = (fs, outputPath, dry, logger, diff, isKept, callback) => {
);
return process.nextTick(callback);
}
- fs.unlink(path, err => {
+ fs.unlink(path, (err) => {
if (err) return handleError(err);
handleParent();
callback();
@@ -360,7 +328,7 @@ const applyDiff = (fs, outputPath, dry, logger, diff, isKept, callback) => {
break;
}
},
- err => {
+ (err) => {
if (err) return callback(err);
callback(undefined, keptAssets);
}
@@ -412,9 +380,9 @@ class CleanPlugin {
typeof keep === "function"
? keep
: typeof keep === "string"
- ? path => path.startsWith(keep)
+ ? (path) => path.startsWith(keep)
: typeof keep === "object" && keep.test
- ? path => keep.test(path)
+ ? (path) => keep.test(path)
: () => false;
// We assume that no external modification happens while the compiler is active
@@ -470,7 +438,7 @@ class CleanPlugin {
* @param {string} path path
* @returns {boolean | void} true, if needs to be kept
*/
- const isKept = path => {
+ const isKept = (path) => {
const result = hooks.keep.call(path);
if (result !== undefined) return result;
return keepFn(path);
@@ -518,5 +486,3 @@ class CleanPlugin {
module.exports = CleanPlugin;
module.exports._getDirectories = getDirectories;
-module.exports._hasFile = hasFile;
-module.exports._isEqualPath = isEqualPath;
diff --git a/lib/CodeGenerationResults.js b/lib/CodeGenerationResults.js
index 3ba4e8028a3..fe2097ea5d3 100644
--- a/lib/CodeGenerationResults.js
+++ b/lib/CodeGenerationResults.js
@@ -39,7 +39,7 @@ class CodeGenerationResults {
throw new Error(
`No code generation entry for ${module.identifier()} (existing entries: ${Array.from(
this.map.keys(),
- m => m.identifier()
+ (m) => m.identifier()
).join(", ")})`
);
}
@@ -50,7 +50,7 @@ class CodeGenerationResults {
throw new Error(
`No unique code generation entry for unspecified runtime for ${module.identifier()} (existing runtimes: ${Array.from(
entry.keys(),
- r => runtimeToString(r)
+ (r) => runtimeToString(r)
).join(", ")}).
Caller might not support runtime-dependent code generation (opt-out via optimization.usedExports: "global").`
);
@@ -66,7 +66,7 @@ Caller might not support runtime-dependent code generation (opt-out via optimiza
runtime
)} for ${module.identifier()} (existing runtimes: ${Array.from(
entry.keys(),
- r => runtimeToString(r)
+ (r) => runtimeToString(r)
).join(", ")})`
);
}
diff --git a/lib/CompatibilityPlugin.js b/lib/CompatibilityPlugin.js
index 759d6a8c534..d5ce1872512 100644
--- a/lib/CompatibilityPlugin.js
+++ b/lib/CompatibilityPlugin.js
@@ -54,7 +54,7 @@ class CompatibilityPlugin {
* @param {CallExpression} expr call expression
* @returns {boolean | void} true when need to handle
*/
- expr => {
+ (expr) => {
// support for browserify style require delegator: "require(o, !0)"
if (expr.arguments.length !== 2) return;
const second = parser.evaluateExpression(expr.arguments[1]);
@@ -90,9 +90,9 @@ class CompatibilityPlugin {
* @param {JavascriptParser} parser the parser
* @returns {void}
*/
- const handler = parser => {
+ const handler = (parser) => {
// Handle nested requires
- parser.hooks.preStatement.tap(PLUGIN_NAME, statement => {
+ parser.hooks.preStatement.tap(PLUGIN_NAME, (statement) => {
if (
statement.type === "FunctionDeclaration" &&
statement.id &&
@@ -118,7 +118,7 @@ class CompatibilityPlugin {
});
parser.hooks.pattern
.for(RuntimeGlobals.require)
- .tap(PLUGIN_NAME, pattern => {
+ .tap(PLUGIN_NAME, (pattern) => {
const newName = `__nested_webpack_require_${
/** @type {Range} */ (pattern.range)[0]
}__`;
@@ -134,7 +134,7 @@ class CompatibilityPlugin {
});
parser.hooks.pattern
.for(RuntimeGlobals.exports)
- .tap(PLUGIN_NAME, pattern => {
+ .tap(PLUGIN_NAME, (pattern) => {
parser.tagVariable(pattern.name, nestedWebpackIdentifierTag, {
name: "__nested_webpack_exports__",
declaration: {
@@ -147,7 +147,7 @@ class CompatibilityPlugin {
});
parser.hooks.expression
.for(nestedWebpackIdentifierTag)
- .tap(PLUGIN_NAME, expr => {
+ .tap(PLUGIN_NAME, (expr) => {
const { name, declaration } =
/** @type {TagData} */
(parser.currentTagData);
diff --git a/lib/Compilation.js b/lib/Compilation.js
index b5f7558ac61..4e39047fe0a 100644
--- a/lib/Compilation.js
+++ b/lib/Compilation.js
@@ -372,7 +372,7 @@ const { isSourceEqual } = require("./util/source");
* @property {false | "none" | "error" | "warn" | "info" | "log" | "verbose"} logging
* @property {((value: string) => boolean)[]} loggingDebug
* @property {boolean} loggingTrace
- * @property {TODO} _env
+ * @property {EXPECTED_ANY} _env
*/
/** @typedef {KnownNormalizedStatsOptions & Omit & Record} NormalizedStatsOptions */
@@ -403,7 +403,7 @@ const deprecatedNormalModuleLoaderHook = util.deprecate(
* @param {Compilation} compilation compilation
* @returns {NormalModuleCompilationHooks["loader"]} hooks
*/
- compilation =>
+ (compilation) =>
require("./NormalModule").getCompilationHooks(compilation).loader,
"Compilation.hooks.normalModuleLoader was moved to NormalModule.getCompilationHooks(compilation).loader",
"DEP_WEBPACK_COMPILATION_NORMAL_MODULE_LOADER_HOOK"
@@ -413,7 +413,7 @@ const deprecatedNormalModuleLoaderHook = util.deprecate(
/**
* @param {ModuleTemplates | undefined} moduleTemplates module templates
*/
-const defineRemovedModuleTemplates = moduleTemplates => {
+const defineRemovedModuleTemplates = (moduleTemplates) => {
Object.defineProperties(moduleTemplates, {
asset: {
enumerable: false,
@@ -437,21 +437,24 @@ const defineRemovedModuleTemplates = moduleTemplates => {
moduleTemplates = undefined;
};
-const byId = compareSelect(c => c.id, compareIds);
+const byId = compareSelect((c) => c.id, compareIds);
const byNameOrHash = concatComparators(
- compareSelect(c => c.name, compareIds),
- compareSelect(c => c.fullHash, compareIds)
+ compareSelect((c) => c.name, compareIds),
+ compareSelect((c) => c.fullHash, compareIds)
);
-const byMessage = compareSelect(err => `${err.message}`, compareStringsNumeric);
+const byMessage = compareSelect(
+ (err) => `${err.message}`,
+ compareStringsNumeric
+);
const byModule = compareSelect(
- err => (err.module && err.module.identifier()) || "",
+ (err) => (err.module && err.module.identifier()) || "",
compareStringsNumeric
);
-const byLocation = compareSelect(err => err.loc, compareLocations);
+const byLocation = compareSelect((err) => err.loc, compareLocations);
const compareErrors = concatComparators(byModule, byLocation, byMessage);
@@ -497,7 +500,7 @@ class Compilation {
* @param {CompilationAssets} assets assets
* @returns {CompilationAssets} new assets
*/
- const popNewAssets = assets => {
+ const popNewAssets = (assets) => {
let newAssets;
for (const file of Object.keys(assets)) {
if (savedAssets.has(file)) continue;
@@ -514,7 +517,7 @@ class Compilation {
call: () => {
savedAssets = new Set(Object.keys(this.assets));
},
- register: tap => {
+ register: (tap) => {
const { type, name } = tap;
const { fn, additionalAssets, ...remainingTap } = tap;
const additionalAssetsFn =
@@ -526,7 +529,7 @@ class Compilation {
switch (type) {
case "sync":
if (additionalAssetsFn) {
- this.hooks.processAdditionalAssets.tap(name, assets => {
+ this.hooks.processAdditionalAssets.tap(name, (assets) => {
if (
/** @type {ProcessedAssets} */
(processedAssets).has(this.assets)
@@ -592,7 +595,7 @@ class Compilation {
* @param {Error} err err
* @returns {void}
*/
- err => {
+ (err) => {
if (err) return callback(err);
if (processedAssets !== undefined) {
processedAssets.add(this.assets);
@@ -612,7 +615,7 @@ class Compilation {
};
case "promise":
if (additionalAssetsFn) {
- this.hooks.processAdditionalAssets.tapPromise(name, assets => {
+ this.hooks.processAdditionalAssets.tapPromise(name, (assets) => {
if (
/** @type {ProcessedAssets} */
(processedAssets).has(this.assets)
@@ -628,7 +631,7 @@ class Compilation {
* @param {CompilationAssets} assets assets
* @returns {Promise} result
*/
- fn: assets => {
+ fn: (assets) => {
const p = fn(assets);
if (!p || !p.then) return p;
return p.then(() => {
@@ -665,14 +668,15 @@ class Compilation {
* @param {string} reason reason
* @returns {string} error message
*/
- const errorMessage =
- reason => `Can't automatically convert plugin using Compilation.hooks.${name} to Compilation.hooks.processAssets because ${reason}.
+ const errorMessage = (
+ reason
+ ) => `Can't automatically convert plugin using Compilation.hooks.${name} to Compilation.hooks.processAssets because ${reason}.
BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a single Compilation.hooks.processAssets hook.`;
/**
* @param {string | (import("tapable").TapOptions & { name: string; } & ProcessAssetsAdditionalOptions)} options hook options
* @returns {import("tapable").TapOptions & { name: string; } & ProcessAssetsAdditionalOptions} modified options
*/
- const getOptions = options => {
+ const getOptions = (options) => {
if (typeof options === "string") options = { name: options };
if (options.stage) {
throw new Error(errorMessage("it's using the 'stage' option"));
@@ -1075,7 +1079,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
this.addModuleQueue = new AsyncQueue({
name: "addModule",
parent: this.processDependenciesQueue,
- getKey: module => module.identifier(),
+ getKey: (module) => module.identifier(),
processor: this._addModule.bind(this)
});
/** @type {AsyncQueue} */
@@ -1199,7 +1203,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
* @param {string} item item
* @returns {LazySet} file dependencies
*/
- item => this.fileDependencies.add(item),
+ (item) => this.fileDependencies.add(item),
"Compilation.compilationDependencies is deprecated (used Compilation.fileDependencies instead)",
"DEP_WEBPACK_COMPILATION_COMPILATION_DEPENDENCIES"
)
@@ -1351,7 +1355,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
/* eslint-enable no-console */
}
},
- childName => {
+ (childName) => {
if (typeof name === "function") {
if (typeof childName === "function") {
return this.getLogger(() => {
@@ -1527,7 +1531,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
this.resolverFactory.get("normal", module.resolveOptions),
/** @type {InputFileSystem} */
(this.inputFileSystem),
- err => {
+ (err) => {
if (currentProfile !== undefined) {
currentProfile.markBuildingEnd();
}
@@ -1538,20 +1542,25 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
if (currentProfile !== undefined) {
currentProfile.markStoringStart();
}
- this._modulesCache.store(module.identifier(), null, module, err => {
- if (currentProfile !== undefined) {
- currentProfile.markStoringEnd();
- }
- if (err) {
- this.hooks.failedModule.call(
- module,
- /** @type {WebpackError} */ (err)
- );
- return callback(new ModuleStoreError(module, err));
+ this._modulesCache.store(
+ module.identifier(),
+ null,
+ module,
+ (err) => {
+ if (currentProfile !== undefined) {
+ currentProfile.markStoringEnd();
+ }
+ if (err) {
+ this.hooks.failedModule.call(
+ module,
+ /** @type {WebpackError} */ (err)
+ );
+ return callback(new ModuleStoreError(module, err));
+ }
+ this.hooks.succeedModule.call(module);
+ return callback();
}
- this.hooks.succeedModule.call(module);
- return callback();
- });
+ );
}
);
}
@@ -1575,7 +1584,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
/**
* @param {DependenciesBlock} block block
*/
- const processDependenciesBlock = block => {
+ const processDependenciesBlock = (block) => {
if (block.dependencies) {
let i = 0;
for (const dep of block.dependencies) {
@@ -1625,7 +1634,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
* @param {WebpackError=} err error
* @returns {void}
*/
- const onDependenciesSorted = err => {
+ const onDependenciesSorted = (err) => {
if (err) return callback(err);
// early exit without changing parallelism back and forth
@@ -1639,7 +1648,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
for (const item of sortedDependencies) {
inProgressTransitive++;
// eslint-disable-next-line no-loop-func
- this.handleModuleCreation(item, err => {
+ this.handleModuleCreation(item, (err) => {
// In V8, the Error objects keep a reference to the functions on the stack. These warnings &
// errors are created inside closures that keep a reference to the Compilation, so errors are
// leaking the Compilation object.
@@ -1661,7 +1670,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
* @param {WebpackError=} err error
* @returns {void}
*/
- const onTransitiveTasksFinished = err => {
+ const onTransitiveTasksFinished = (err) => {
if (err) return callback(err);
this.processDependenciesQueue.decreaseParallelism();
@@ -1738,7 +1747,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
module,
dep,
cachedModule,
- err => {
+ (err) => {
if (err) {
if (inProgressTransitive <= 0) return;
inProgressTransitive = -1;
@@ -1783,7 +1792,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
* @param {Dependency} dep dependency
* @returns {void}
*/
- const processDependencyForResolving = dep => {
+ const processDependencyForResolving = (dep) => {
const resourceIdent = dep.getResourceIdentifier();
if (resourceIdent !== undefined && resourceIdent !== null) {
const category = dep.category;
@@ -1982,7 +1991,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
};
if (err) {
if (factoryResult) applyFactoryResultDependencies();
- if (dependencies.every(d => d.optional)) {
+ if (dependencies.every((d) => d.optional)) {
this.warnings.push(err);
return callback();
}
@@ -2136,7 +2145,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
}
}
- this.buildModule(module, err => {
+ this.buildModule(module, (err) => {
if (creatingModuleDuringBuildSet !== undefined) {
creatingModuleDuringBuildSet.delete(module);
}
@@ -2160,7 +2169,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
return callback(null, module);
}
- this.processModuleDependencies(module, err => {
+ this.processModuleDependencies(module, (err) => {
if (err) {
return callback(err);
}
@@ -2238,7 +2247,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
originModule,
err,
/** @type {DependencyLocation} */
- (dependencies.map(d => d.loc).find(Boolean))
+ (dependencies.map((d) => d.loc).find(Boolean))
);
return callback(notFoundError, factoryResult ? result : undefined);
}
@@ -2453,9 +2462,9 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
const oldBlocks = [...module.blocks];
module.invalidateBuild();
this.buildQueue.invalidate(module);
- this.buildModule(module, err => {
+ this.buildModule(module, (err) => {
if (err) {
- return this.hooks.finishRebuildingModule.callAsync(module, err2 => {
+ return this.hooks.finishRebuildingModule.callAsync(module, (err2) => {
if (err2) {
callback(
makeWebpackError(err2, "Compilation.hooks.finishRebuildingModule")
@@ -2468,13 +2477,13 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
this.processDependenciesQueue.invalidate(module);
this.moduleGraph.unfreeze();
- this.processModuleDependencies(module, err => {
+ this.processModuleDependencies(module, (err) => {
if (err) return callback(err);
this.removeReasonsOfDependencyBlock(module, {
dependencies: oldDependencies,
blocks: oldBlocks
});
- this.hooks.finishRebuildingModule.callAsync(module, err2 => {
+ this.hooks.finishRebuildingModule.callAsync(module, (err2) => {
if (err2) {
callback(
makeWebpackError(err2, "Compilation.hooks.finishRebuildingModule")
@@ -2511,7 +2520,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
* @param {Module} module module
* @returns {WeakReferences | undefined} references
*/
- const computeReferences = module => {
+ const computeReferences = (module) => {
/** @type {WeakReferences | undefined} */
let references;
for (const connection of moduleGraph.getOutgoingConnections(module)) {
@@ -2604,7 +2613,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
* @param {readonly ModuleGraphConnection[]} connections connections
* @returns {symbol|boolean} result
*/
- const reduceAffectType = connections => {
+ const reduceAffectType = (connections) => {
let affected = false;
for (const { dependency } of connections) {
if (!dependency) continue;
@@ -2684,7 +2693,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
* @param {Module} module module
* @returns {References} references
*/
- const computeReferences = module => {
+ const computeReferences = (module) => {
const id = /** @type {ModuleId} */ (chunkGraph.getModuleId(module));
/** @type {Map | undefined} */
let modules;
@@ -2804,27 +2813,27 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
p.range(
profile.buildingStartTime,
profile.buildingEndTime,
- f => (profile.buildingParallelismFactor = f)
+ (f) => (profile.buildingParallelismFactor = f)
);
p.range(
profile.factoryStartTime,
profile.factoryEndTime,
- f => (profile.factoryParallelismFactor = f)
+ (f) => (profile.factoryParallelismFactor = f)
);
p.range(
profile.integrationStartTime,
profile.integrationEndTime,
- f => (profile.integrationParallelismFactor = f)
+ (f) => (profile.integrationParallelismFactor = f)
);
p.range(
profile.storingStartTime,
profile.storingEndTime,
- f => (profile.storingParallelismFactor = f)
+ (f) => (profile.storingParallelismFactor = f)
);
p.range(
profile.restoringStartTime,
profile.restoringEndTime,
- f => (profile.restoringParallelismFactor = f)
+ (f) => (profile.restoringParallelismFactor = f)
);
if (profile.additionalFactoryTimes) {
for (const { start, end } of profile.additionalFactoryTimes) {
@@ -2832,7 +2841,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
p.range(
start,
end,
- f =>
+ (f) =>
(profile.additionalFactoriesParallelismFactor += f * influence)
);
}
@@ -2955,33 +2964,33 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
};
logNormalSummary(
"resolve to new modules",
- p => p.factory,
- p => p.factoryParallelismFactor
+ (p) => p.factory,
+ (p) => p.factoryParallelismFactor
);
logNormalSummary(
"resolve to existing modules",
- p => p.additionalFactories,
- p => p.additionalFactoriesParallelismFactor
+ (p) => p.additionalFactories,
+ (p) => p.additionalFactoriesParallelismFactor
);
logNormalSummary(
"integrate modules",
- p => p.restoring,
- p => p.restoringParallelismFactor
+ (p) => p.restoring,
+ (p) => p.restoringParallelismFactor
);
logByLoadersSummary(
"build modules",
- p => p.building,
- p => p.buildingParallelismFactor
+ (p) => p.building,
+ (p) => p.buildingParallelismFactor
);
logNormalSummary(
"store modules",
- p => p.storing,
- p => p.storingParallelismFactor
+ (p) => p.storing,
+ (p) => p.storingParallelismFactor
);
logNormalSummary(
"restore modules",
- p => p.restoring,
- p => p.restoringParallelismFactor
+ (p) => p.restoring,
+ (p) => p.restoringParallelismFactor
);
this.logger.timeEnd("finish module profiles");
}
@@ -2990,7 +2999,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
this.logger.timeEnd("compute affected modules");
this.logger.time("finish modules");
const { modules, moduleMemCaches } = this;
- this.hooks.finishModules.callAsync(modules, err => {
+ this.hooks.finishModules.callAsync(modules, (err) => {
this.logger.timeEnd("finish modules");
if (err) return callback(/** @type {WebpackError} */ (err));
@@ -3061,7 +3070,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
* @param {WebpackError=} err err
* @returns {void}
*/
- const finalCallback = err => {
+ const finalCallback = (err) => {
this.factorizeQueue.clear();
this.buildQueue.clear();
this.rebuildQueue.clear();
@@ -3139,11 +3148,11 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
* @param {Dependency[]} deps deps
* @returns {Module[]} sorted deps
*/
- const mapAndSort = deps =>
+ const mapAndSort = (deps) =>
/** @type {Module[]} */
- (deps.map(dep => this.moduleGraph.getModule(dep)).filter(Boolean)).sort(
- compareModulesByIdentifier
- );
+ (
+ deps.map((dep) => this.moduleGraph.getModule(dep)).filter(Boolean)
+ ).sort(compareModulesByIdentifier);
const includedModules = [
...mapAndSort(this.globalEntry.includeDependencies),
...mapAndSort(includeDependencies)
@@ -3250,7 +3259,7 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
}
this.hooks.afterOptimizeChunks.call(this.chunks, this.chunkGroups);
- this.hooks.optimizeTree.callAsync(this.chunks, this.modules, err => {
+ this.hooks.optimizeTree.callAsync(this.chunks, this.modules, (err) => {
if (err) {
return finalCallback(
makeWebpackError(err, "Compilation.hooks.optimizeTree")
@@ -3262,7 +3271,7 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
this.hooks.optimizeChunkModules.callAsync(
this.chunks,
this.modules,
- err => {
+ (err) => {
if (err) {
return finalCallback(
makeWebpackError(err, "Compilation.hooks.optimizeChunkModules")
@@ -3325,7 +3334,7 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
this.logger.time("code generation");
this.hooks.beforeCodeGeneration.call();
- this.codeGeneration(err => {
+ this.codeGeneration((err) => {
if (err) {
return finalCallback(err);
}
@@ -3344,7 +3353,7 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
this.hooks.afterHash.call();
this.logger.timeEnd("hashing");
- this._runCodeGenerationJobs(codeGenerationJobs, err => {
+ this._runCodeGenerationJobs(codeGenerationJobs, (err) => {
if (err) {
return finalCallback(err);
}
@@ -3367,7 +3376,7 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
const cont = () => {
this.logger.time("process assets");
- this.hooks.processAssets.callAsync(this.assets, err => {
+ this.hooks.processAssets.callAsync(this.assets, (err) => {
if (err) {
return finalCallback(
makeWebpackError(err, "Compilation.hooks.processAssets")
@@ -3403,7 +3412,7 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
this.unseal();
return this.seal(callback);
}
- return this.hooks.afterSeal.callAsync(err => {
+ return this.hooks.afterSeal.callAsync((err) => {
if (err) {
return finalCallback(
makeWebpackError(err, "Compilation.hooks.afterSeal")
@@ -3418,7 +3427,7 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
this.logger.time("create chunk assets");
if (this.hooks.shouldGenerateChunkAssets.call() !== false) {
this.hooks.beforeChunkAssets.call();
- this.createChunkAssets(err => {
+ this.createChunkAssets((err) => {
this.logger.timeEnd("create chunk assets");
if (err) {
return finalCallback(err);
@@ -3542,7 +3551,7 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
if (
codeGenerationDependencies !== undefined &&
(notCodeGeneratedModules === undefined ||
- codeGenerationDependencies.some(dep => {
+ codeGenerationDependencies.some((dep) => {
const referencedModule = /** @type {Module} */ (
moduleGraph.getModule(dep)
);
@@ -3574,7 +3583,7 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
}
);
},
- err => {
+ (err) => {
if (err) return callback(err);
if (delayedJobs.length > 0) {
if (delayedJobs.length === jobs.length) {
@@ -3583,7 +3592,7 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
new Error(
`Unable to make progress during code generation because of circular code generation dependency: ${Array.from(
delayedModules,
- m => m.identifier()
+ (m) => m.identifier()
).join(", ")}`
)
)
@@ -3597,7 +3606,7 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
}
if (errors.length > 0) {
errors.sort(
- compareSelect(err => err.module, compareModulesByIdentifier)
+ compareSelect((err) => err.module, compareModulesByIdentifier)
);
for (const error of errors) {
this.errors.push(error);
@@ -3644,7 +3653,7 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
) {
let codeGenerated = false;
const cache = new MultiItemCache(
- runtimes.map(runtime =>
+ runtimes.map((runtime) =>
this._codeGenerationCache.getItemCache(
`${module.identifier()}|${getRuntimeKey(runtime)}`,
`${hash}|${dependencyTemplates.getHash()}`
@@ -3683,7 +3692,7 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
results.add(module, runtime, result);
}
if (!cachedResult) {
- cache.store(result, err =>
+ cache.store(result, (err) =>
callback(/** @type {WebpackError} */ (err), codeGenerated)
);
} else {
@@ -4031,7 +4040,7 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
* @param {Module} module module for processing
* @returns {void}
*/
- const processModule = module => {
+ const processModule = (module) => {
if (!moduleGraph.setDepthIfLower(module, depth)) return;
queue.add(module);
};
@@ -4157,7 +4166,7 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
/**
* @param {Dependency} d dependency to (maybe) patch up
*/
- const iteratorDependency = d => {
+ const iteratorDependency = (d) => {
const depModule = this.moduleGraph.getModule(d);
if (!depModule) {
return;
@@ -4190,7 +4199,7 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
/**
* @param {Entrypoint} ep an entrypoint
*/
- const processEntrypoint = ep => {
+ const processEntrypoint = (ep) => {
const runtime = /** @type {string} */ (ep.options.runtime || ep.name);
const chunk = /** @type {Chunk} */ (ep.getRuntimeChunk());
chunkGraph.setRuntimeId(runtime, /** @type {ChunkId} */ (chunk.id));
@@ -4273,7 +4282,9 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
}
}
if (errors.length > 0) {
- errors.sort(compareSelect(err => err.module, compareModulesByIdentifier));
+ errors.sort(
+ compareSelect((err) => err.module, compareModulesByIdentifier)
+ );
for (const error of errors) {
this.errors.push(error);
}
@@ -4410,7 +4421,7 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
for (const info of runtimeChunksMap.values()) {
for (const other of new Set(
[...info.chunk.getAllReferencedAsyncEntrypoints()].map(
- e => e.chunks[e.chunks.length - 1]
+ (e) => e.chunks[e.chunks.length - 1]
)
)) {
const otherInfo =
@@ -4463,11 +4474,11 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
circularRuntimeChunkInfo.push(info);
}
}
- circularRuntimeChunkInfo.sort(compareSelect(i => i.chunk, byId));
+ circularRuntimeChunkInfo.sort(compareSelect((i) => i.chunk, byId));
const err =
new WebpackError(`Circular dependency between chunks with runtime (${Array.from(
circularRuntimeChunkInfo,
- c => c.chunk.name || c.chunk.id
+ (c) => c.chunk.name || c.chunk.id
).join(", ")})
This prevents using hashes of each other and should be avoided.`);
err.chunk = circularRuntimeChunkInfo[0].chunk;
@@ -4487,7 +4498,7 @@ This prevents using hashes of each other and should be avoided.`);
/**
* @param {Chunk} chunk chunk
*/
- const processChunk = chunk => {
+ const processChunk = (chunk) => {
// Last minute module hash generation for modules that depend on chunk hashes
this.logger.time("hashing: hash runtime modules");
const runtime = chunk.runtime;
@@ -4564,7 +4575,9 @@ This prevents using hashes of each other and should be avoided.`);
for (const chunk of runtimeChunks) processChunk(chunk);
for (const chunk of initialChunks) processChunk(chunk);
if (errors.length > 0) {
- errors.sort(compareSelect(err => err.module, compareModulesByIdentifier));
+ errors.sort(
+ compareSelect((err) => err.module, compareModulesByIdentifier)
+ );
for (const error of errors) {
this.errors.push(error);
}
@@ -4671,7 +4684,7 @@ This prevents using hashes of each other and should be avoided.`);
/**
* @param {string} name name
*/
- const remove = name => {
+ const remove = (name) => {
const relatedIn = this._assetsRelatedIn.get(name);
if (relatedIn === undefined) return;
const entry = relatedIn.get(key);
@@ -4696,7 +4709,7 @@ This prevents using hashes of each other and should be avoided.`);
/**
* @param {string} name name
*/
- const add = name => {
+ const add = (name) => {
let relatedIn = this._assetsRelatedIn.get(name);
if (relatedIn === undefined) {
this._assetsRelatedIn.set(name, (relatedIn = new Map()));
@@ -4783,7 +4796,7 @@ This prevents using hashes of each other and should be avoided.`);
const entry = related[key];
let newEntry;
if (Array.isArray(entry)) {
- newEntry = entry.map(x => (x === file ? newFile : x));
+ newEntry = entry.map((x) => (x === file ? newFile : x));
} else if (entry === file) {
newEntry = newFile;
} else {
@@ -4837,7 +4850,7 @@ This prevents using hashes of each other and should be avoided.`);
/**
* @param {string} file file
*/
- const checkUsedAndDelete = file => {
+ const checkUsedAndDelete = (file) => {
if (!this._assetsRelatedIn.has(file)) {
this.deleteAsset(file);
}
@@ -4987,7 +5000,7 @@ This prevents using hashes of each other and should be avoided.`);
* @param {Error} err error
* @returns {void}
*/
- const errorAndCallback = err => {
+ const errorAndCallback = (err) => {
const filename =
file ||
(typeof file === "string"
@@ -5068,7 +5081,7 @@ This prevents using hashes of each other and should be avoided.`);
chunk
});
if (source !== sourceFromCache) {
- assetCacheItem.store(source, err => {
+ assetCacheItem.store(source, (err) => {
if (err) return errorAndCallback(err);
inTry = false;
return callback();
@@ -5190,9 +5203,9 @@ This prevents using hashes of each other and should be avoided.`);
modules,
10,
(module, push, callback) => {
- this.buildQueue.waitFor(module, err => {
+ this.buildQueue.waitFor(module, (err) => {
if (err) return callback(err);
- this.processDependenciesQueue.waitFor(module, err => {
+ this.processDependenciesQueue.waitFor(module, (err) => {
if (err) return callback(err);
for (const { module: m } of this.moduleGraph.getOutgoingConnections(
module
@@ -5205,7 +5218,7 @@ This prevents using hashes of each other and should be avoided.`);
});
});
},
- err => {
+ (err) => {
if (err) return callback(/** @type {WebpackError} */ (err));
// Create new chunk graph, chunk and entrypoint for the build time execution
@@ -5288,7 +5301,7 @@ This prevents using hashes of each other and should be avoided.`);
const reportErrors = () => {
if (errors.length > 0) {
errors.sort(
- compareSelect(err => err.module, compareModulesByIdentifier)
+ compareSelect((err) => err.module, compareModulesByIdentifier)
);
for (const error of errors) {
this.errors.push(error);
@@ -5298,7 +5311,7 @@ This prevents using hashes of each other and should be avoided.`);
};
// Generate code for all aggregated modules
- asyncLib.eachLimit(modules, 10, codeGen, err => {
+ asyncLib.eachLimit(modules, 10, codeGen, (err) => {
if (err) return callback(err);
reportErrors();
@@ -5334,7 +5347,7 @@ This prevents using hashes of each other and should be avoided.`);
}
// Generate code for all runtime modules
- asyncLib.eachLimit(runtimeModules, 10, codeGen, err => {
+ asyncLib.eachLimit(runtimeModules, 10, codeGen, (err) => {
if (err) return callback(err);
reportErrors();
@@ -5410,7 +5423,7 @@ This prevents using hashes of each other and should be avoided.`);
callback
);
},
- err => {
+ (err) => {
if (err) return callback(err);
/** @type {ExecuteModuleExports | undefined} */
@@ -5422,7 +5435,7 @@ This prevents using hashes of each other and should be avoided.`);
} = this.outputOptions;
/** @type {WebpackRequire} */
- const __webpack_require__ = id => {
+ const __webpack_require__ = (id) => {
const cached = moduleCache[id];
if (cached !== undefined) {
if (cached.error) throw cached.error;
@@ -5656,7 +5669,7 @@ Object.defineProperty(compilationPrototype, "cache", {
/**
* @param {EXPECTED_ANY} _v value
*/
- _v => {},
+ (_v) => {},
"Compilation.cache was removed in favor of Compilation.getCache()",
"DEP_WEBPACK_COMPILATION_CACHE"
)
diff --git a/lib/Compiler.js b/lib/Compiler.js
index fb509a8dc61..f87921e8139 100644
--- a/lib/Compiler.js
+++ b/lib/Compiler.js
@@ -125,7 +125,7 @@ const webpack = require(".");
* @param {string[]} array an array
* @returns {boolean} true, if the array is sorted
*/
-const isSorted = array => {
+const isSorted = (array) => {
for (let i = 1; i < array.length; i++) {
if (array[i - 1] > array[i]) return false;
}
@@ -154,7 +154,7 @@ const sortObject = (obj, keys) => {
const includesHash = (filename, hashes) => {
if (!hashes) return false;
if (Array.isArray(hashes)) {
- return hashes.some(hash => filename.includes(hash));
+ return hashes.some((hash) => filename.includes(hash));
}
return filename.includes(hashes);
};
@@ -388,7 +388,7 @@ class Compiler {
this.infrastructureLogger(name, type, args);
}
},
- childName => {
+ (childName) => {
if (typeof name === "function") {
if (typeof childName === "function") {
return this.getInfrastructureLogger(() => {
@@ -540,7 +540,7 @@ class Compiler {
compilation.startTime = startTime;
compilation.endTime = Date.now();
const stats = new Stats(compilation);
- this.hooks.done.callAsync(stats, err => {
+ this.hooks.done.callAsync(stats, (err) => {
if (err) return finalCallback(err);
return finalCallback(null, stats);
});
@@ -550,7 +550,7 @@ class Compiler {
process.nextTick(() => {
logger = compilation.getLogger("webpack.Compiler");
logger.time("emitAssets");
- this.emitAssets(compilation, err => {
+ this.emitAssets(compilation, (err) => {
/** @type {Logger} */
(logger).timeEnd("emitAssets");
if (err) return finalCallback(err);
@@ -563,12 +563,12 @@ class Compiler {
/** @type {Logger} */
(logger).time("done hook");
const stats = new Stats(compilation);
- this.hooks.done.callAsync(stats, err => {
+ this.hooks.done.callAsync(stats, (err) => {
/** @type {Logger} */
(logger).timeEnd("done hook");
if (err) return finalCallback(err);
- this.hooks.additionalPass.callAsync(err => {
+ this.hooks.additionalPass.callAsync((err) => {
if (err) return finalCallback(err);
this.compile(onCompiled);
});
@@ -578,7 +578,7 @@ class Compiler {
/** @type {Logger} */
(logger).time("emitRecords");
- this.emitRecords(err => {
+ this.emitRecords((err) => {
/** @type {Logger} */
(logger).timeEnd("emitRecords");
if (err) return finalCallback(err);
@@ -588,13 +588,13 @@ class Compiler {
/** @type {Logger} */
(logger).time("done hook");
const stats = new Stats(compilation);
- this.hooks.done.callAsync(stats, err => {
+ this.hooks.done.callAsync(stats, (err) => {
/** @type {Logger} */
(logger).timeEnd("done hook");
if (err) return finalCallback(err);
this.cache.storeBuildDependencies(
compilation.buildDependencies,
- err => {
+ (err) => {
if (err) return finalCallback(err);
return finalCallback(null, stats);
}
@@ -606,13 +606,13 @@ class Compiler {
};
const run = () => {
- this.hooks.beforeRun.callAsync(this, err => {
+ this.hooks.beforeRun.callAsync(this, (err) => {
if (err) return finalCallback(err);
- this.hooks.run.callAsync(this, err => {
+ this.hooks.run.callAsync(this, (err) => {
if (err) return finalCallback(err);
- this.readRecords(err => {
+ this.readRecords((err) => {
if (err) return finalCallback(err);
this.compile(onCompiled);
@@ -622,7 +622,7 @@ class Compiler {
};
if (this.idle) {
- this.cache.endIdle(err => {
+ this.cache.endIdle((err) => {
if (err) return finalCallback(err);
this.idle = false;
@@ -706,7 +706,7 @@ class Compiler {
* @param {Error=} err error
* @returns {void}
*/
- const emitFiles = err => {
+ const emitFiles = (err) => {
if (err) return callback(err);
const assets = compilation.getAssets();
@@ -739,7 +739,7 @@ class Compiler {
* @param {Error=} err error
* @returns {void}
*/
- const writeOut = err => {
+ const writeOut = (err) => {
if (err) return callback(err);
const targetPath = join(
/** @type {OutputFileSystem} */
@@ -838,9 +838,9 @@ ${other}`);
* @param {Buffer} content content to be written
* @returns {void}
*/
- const doWrite = content => {
+ const doWrite = (content) => {
/** @type {OutputFileSystem} */
- (this.outputFileSystem).writeFile(targetPath, content, err => {
+ (this.outputFileSystem).writeFile(targetPath, content, (err) => {
if (err) return callback(err);
// information marker that the asset has been emitted
@@ -871,7 +871,7 @@ ${other}`);
/**
* @param {number} size size
*/
- const updateWithReplacementSource = size => {
+ const updateWithReplacementSource = (size) => {
updateFileWithReplacementSource(
file,
/** @type {CacheEntry} */ (cacheEntry),
@@ -915,7 +915,7 @@ ${other}`);
* @param {IStats} stats stats
* @returns {void}
*/
- const processExistingFile = stats => {
+ const processExistingFile = (stats) => {
// skip emitting if it's already there and an immutable file
if (immutable) {
updateWithReplacementSource(/** @type {number} */ (stats.size));
@@ -1015,7 +1015,7 @@ ${other}`);
writeOut();
}
},
- err => {
+ (err) => {
// Clear map to free up memory
caseInsensitiveMap.clear();
if (err) {
@@ -1025,7 +1025,7 @@ ${other}`);
this._assetEmittingPreviousFiles = allTargetPaths;
- this.hooks.afterEmit.callAsync(compilation, err => {
+ this.hooks.afterEmit.callAsync(compilation, (err) => {
if (err) return callback(err);
return callback();
@@ -1034,7 +1034,7 @@ ${other}`);
);
};
- this.hooks.emit.callAsync(compilation, err => {
+ this.hooks.emit.callAsync(compilation, (err) => {
if (err) return callback(err);
outputPath = compilation.getPath(this.outputPath, {});
mkdirp(
@@ -1054,10 +1054,10 @@ ${other}`);
if (this.recordsOutputPath) {
asyncLib.parallel(
[
- cb => this.hooks.emitRecords.callAsync(cb),
+ (cb) => this.hooks.emitRecords.callAsync(cb),
this._emitRecords.bind(this)
],
- err => callback(err)
+ (err) => callback(err)
);
} else {
this.hooks.emitRecords.callAsync(callback);
@@ -1111,7 +1111,7 @@ ${other}`);
mkdirp(
/** @type {OutputFileSystem} */ (this.outputFileSystem),
recordsOutputPathDirectory,
- err => {
+ (err) => {
if (err) return callback(err);
writeFile();
}
@@ -1127,10 +1127,10 @@ ${other}`);
if (this.recordsInputPath) {
asyncLib.parallel(
[
- cb => this.hooks.readRecords.callAsync(cb),
+ (cb) => this.hooks.readRecords.callAsync(cb),
this._readRecords.bind(this)
],
- err => callback(err)
+ (err) => callback(err)
);
} else {
this.records = {};
@@ -1154,7 +1154,7 @@ ${other}`);
return callback();
}
/** @type {InputFileSystem} */
- (this.inputFileSystem).stat(this.recordsInputPath, err => {
+ (this.inputFileSystem).stat(this.recordsInputPath, (err) => {
// It doesn't exist
// We can ignore this.
if (err) return callback();
@@ -1339,7 +1339,7 @@ ${other}`);
*/
compile(callback) {
const params = this.newCompilationParams();
- this.hooks.beforeCompile.callAsync(params, err => {
+ this.hooks.beforeCompile.callAsync(params, (err) => {
if (err) return callback(err);
this.hooks.compile.call(params);
@@ -1349,28 +1349,28 @@ ${other}`);
const logger = compilation.getLogger("webpack.Compiler");
logger.time("make hook");
- this.hooks.make.callAsync(compilation, err => {
+ this.hooks.make.callAsync(compilation, (err) => {
logger.timeEnd("make hook");
if (err) return callback(err);
logger.time("finish make hook");
- this.hooks.finishMake.callAsync(compilation, err => {
+ this.hooks.finishMake.callAsync(compilation, (err) => {
logger.timeEnd("finish make hook");
if (err) return callback(err);
process.nextTick(() => {
logger.time("finish compilation");
- compilation.finish(err => {
+ compilation.finish((err) => {
logger.timeEnd("finish compilation");
if (err) return callback(err);
logger.time("seal compilation");
- compilation.seal(err => {
+ compilation.seal((err) => {
logger.timeEnd("seal compilation");
if (err) return callback(err);
logger.time("afterCompile hook");
- this.hooks.afterCompile.callAsync(compilation, err => {
+ this.hooks.afterCompile.callAsync(compilation, (err) => {
logger.timeEnd("afterCompile hook");
if (err) return callback(err);
@@ -1391,12 +1391,12 @@ ${other}`);
close(callback) {
if (this.watching) {
// When there is still an active watching, close this first
- this.watching.close(_err => {
+ this.watching.close((_err) => {
this.close(callback);
});
return;
}
- this.hooks.shutdown.callAsync(err => {
+ this.hooks.shutdown.callAsync((err) => {
if (err) return callback(err);
// Get rid of reference to last compilation to avoid leaking memory
// We can't run this._cleanupLastCompilation() as the Stats to this compilation
diff --git a/lib/ConcatenationScope.js b/lib/ConcatenationScope.js
index 76b0a1dde56..e14add3899f 100644
--- a/lib/ConcatenationScope.js
+++ b/lib/ConcatenationScope.js
@@ -30,8 +30,9 @@ class ConcatenationScope {
/**
* @param {ModuleInfo[] | Map} modulesMap all module info by module
* @param {ConcatenatedModuleInfo} currentModule the current module info
+ * @param {Set} usedNames all used names
*/
- constructor(modulesMap, currentModule) {
+ constructor(modulesMap, currentModule, usedNames) {
this._currentModule = currentModule;
if (Array.isArray(modulesMap)) {
const map = new Map();
@@ -40,6 +41,7 @@ class ConcatenationScope {
}
modulesMap = map;
}
+ this.usedNames = usedNames;
this._modulesMap = modulesMap;
}
@@ -77,6 +79,30 @@ class ConcatenationScope {
}
}
+ /**
+ * @param {string} exportName name of the export
+ * @returns {string | undefined} the expression of the export
+ */
+ getRawExport(exportName) {
+ if (!this._currentModule.rawExportMap) {
+ return undefined;
+ }
+ return this._currentModule.rawExportMap.get(exportName);
+ }
+
+ /**
+ * @param {string} exportName name of the export
+ * @param {string} expression expression to be used
+ */
+ setRawExportMap(exportName, expression) {
+ if (!this._currentModule.rawExportMap) {
+ this._currentModule.rawExportMap = new Map();
+ }
+ if (this._currentModule.rawExportMap.has(exportName)) {
+ this._currentModule.rawExportMap.set(exportName, expression);
+ }
+ }
+
/**
* @param {string} symbol identifier of the export in source code
*/
@@ -84,6 +110,18 @@ class ConcatenationScope {
this._currentModule.namespaceExportSymbol = symbol;
}
+ /**
+ * @param {string} symbol identifier of the export in source code
+ * @returns {boolean} registered success
+ */
+ registerUsedName(symbol) {
+ if (this.usedNames.has(symbol)) {
+ return false;
+ }
+ this.usedNames.add(symbol);
+ return true;
+ }
+
/**
* @param {Module} module the referenced module
* @param {Partial} options options
diff --git a/lib/ConstPlugin.js b/lib/ConstPlugin.js
index 04cca9430a3..82ac18cac93 100644
--- a/lib/ConstPlugin.js
+++ b/lib/ConstPlugin.js
@@ -159,9 +159,9 @@ class ConstPlugin {
/**
* @param {JavascriptParser} parser the parser
*/
- const handler = parser => {
- parser.hooks.terminate.tap(PLUGIN_NAME, _statement => true);
- parser.hooks.statementIf.tap(PLUGIN_NAME, statement => {
+ const handler = (parser) => {
+ parser.hooks.terminate.tap(PLUGIN_NAME, (_statement) => true);
+ parser.hooks.statementIf.tap(PLUGIN_NAME, (statement) => {
if (parser.scope.isAsmJs) return;
const param = parser.evaluateExpression(statement.test);
const bool = param.asBool();
@@ -185,7 +185,7 @@ class ConstPlugin {
return bool;
}
});
- parser.hooks.unusedStatement.tap(PLUGIN_NAME, statement => {
+ parser.hooks.unusedStatement.tap(PLUGIN_NAME, (statement) => {
if (
parser.scope.isAsmJs ||
// Check top level scope here again
@@ -198,7 +198,7 @@ class ConstPlugin {
});
parser.hooks.expressionConditionalOperator.tap(
PLUGIN_NAME,
- expression => {
+ (expression) => {
if (parser.scope.isAsmJs) return;
const param = parser.evaluateExpression(expression.test);
const bool = param.asBool();
@@ -239,7 +239,7 @@ class ConstPlugin {
);
parser.hooks.expressionLogicalOperator.tap(
PLUGIN_NAME,
- expression => {
+ (expression) => {
if (parser.scope.isAsmJs) return;
if (
expression.operator === "&&" ||
@@ -381,7 +381,7 @@ class ConstPlugin {
}
}
);
- parser.hooks.optionalChaining.tap(PLUGIN_NAME, expr => {
+ parser.hooks.optionalChaining.tap(PLUGIN_NAME, (expr) => {
/** @type {Expression[]} */
const optionalExpressionsStack = [];
/** @type {Expression | Super} */
@@ -441,7 +441,7 @@ class ConstPlugin {
});
parser.hooks.evaluateIdentifier
.for("__resourceQuery")
- .tap(PLUGIN_NAME, expr => {
+ .tap(PLUGIN_NAME, (expr) => {
if (parser.scope.isAsmJs) return;
if (!parser.state.module) return;
return evaluateToString(
@@ -450,7 +450,7 @@ class ConstPlugin {
});
parser.hooks.expression
.for("__resourceQuery")
- .tap(PLUGIN_NAME, expr => {
+ .tap(PLUGIN_NAME, (expr) => {
if (parser.scope.isAsmJs) return;
if (!parser.state.module) return;
const dep = new CachedConstDependency(
@@ -467,7 +467,7 @@ class ConstPlugin {
parser.hooks.evaluateIdentifier
.for("__resourceFragment")
- .tap(PLUGIN_NAME, expr => {
+ .tap(PLUGIN_NAME, (expr) => {
if (parser.scope.isAsmJs) return;
if (!parser.state.module) return;
return evaluateToString(
@@ -476,7 +476,7 @@ class ConstPlugin {
});
parser.hooks.expression
.for("__resourceFragment")
- .tap(PLUGIN_NAME, expr => {
+ .tap(PLUGIN_NAME, (expr) => {
if (parser.scope.isAsmJs) return;
if (!parser.state.module) return;
const dep = new CachedConstDependency(
diff --git a/lib/ContextExclusionPlugin.js b/lib/ContextExclusionPlugin.js
index c9ad952e143..6bd57c6e0d2 100644
--- a/lib/ContextExclusionPlugin.js
+++ b/lib/ContextExclusionPlugin.js
@@ -23,9 +23,9 @@ class ContextExclusionPlugin {
* @returns {void}
*/
apply(compiler) {
- compiler.hooks.contextModuleFactory.tap(PLUGIN_NAME, cmf => {
- cmf.hooks.contextModuleFiles.tap(PLUGIN_NAME, files =>
- files.filter(filePath => !this.negativeMatcher.test(filePath))
+ compiler.hooks.contextModuleFactory.tap(PLUGIN_NAME, (cmf) => {
+ cmf.hooks.contextModuleFiles.tap(PLUGIN_NAME, (files) =>
+ files.filter((filePath) => !this.negativeMatcher.test(filePath))
);
});
}
diff --git a/lib/ContextModule.js b/lib/ContextModule.js
index 6cbbc7aa0e2..207854d4d1f 100644
--- a/lib/ContextModule.js
+++ b/lib/ContextModule.js
@@ -283,7 +283,7 @@ class ContextModule extends Module {
identifier = `${requestShortener.shorten(`${this.options.resource}`)}/`;
} else {
identifier = this.options.resource
- .map(r => `${requestShortener.shorten(r)}/`)
+ .map((r) => `${requestShortener.shorten(r)}/`)
.join(" ");
}
if (this.options.resourceQuery) {
@@ -309,7 +309,7 @@ class ContextModule extends Module {
}
if (this.options.referencedExports) {
identifier += ` referencedExports: ${this.options.referencedExports
- .map(e => e.join("."))
+ .map((e) => e.join("."))
.join(", ")}`;
}
if (this.options.chunkName) {
@@ -355,7 +355,7 @@ class ContextModule extends Module {
identifier = "false";
} else {
identifier = this.options.resource
- .map(res =>
+ .map((res) =>
contextify(options.context, res, options.associatedObjectForCache)
)
.join(" ");
@@ -386,7 +386,7 @@ class ContextModule extends Module {
}
if (this.options.referencedExports) {
identifier += ` referencedExports: ${this.options.referencedExports
- .map(e => e.join("."))
+ .map((e) => e.join("."))
.join(", ")}`;
}
@@ -466,7 +466,7 @@ class ContextModule extends Module {
}
dependencies.sort(
concatComparators(
- compareSelect(a => a.loc, compareLocations),
+ compareSelect((a) => a.loc, compareLocations),
keepOriginalOrder(this.dependencies)
)
);
@@ -588,7 +588,7 @@ class ContextModule extends Module {
const sortedDependencies =
/** @type {ContextElementDependency[]} */
(dependencies)
- .filter(dependency => moduleGraph.getModule(dependency))
+ .filter((dependency) => moduleGraph.getModule(dependency))
.sort((a, b) => {
if (a.userRequest === b.userRequest) {
return 0;
@@ -621,7 +621,8 @@ class ContextModule extends Module {
// therefore the order of this is !important!
const sortedModules = dependencies
.map(
- dependency => /** @type {Module} */ (moduleGraph.getModule(dependency))
+ (dependency) =>
+ /** @type {Module} */ (moduleGraph.getModule(dependency))
)
.filter(Boolean)
.sort(comparator);
@@ -945,7 +946,7 @@ module.exports = webpackAsyncContext;`;
let hasMultipleOrNoChunks = false;
let hasNoChunk = true;
const fakeMap = this.getFakeMap(
- blocks.map(b => b.dependencies[0]),
+ blocks.map((b) => b.dependencies[0]),
chunkGraph
);
const hasFakeMap = typeof fakeMap === "object";
@@ -954,7 +955,7 @@ module.exports = webpackAsyncContext;`;
* @type {Item[]}
*/
const items = blocks
- .map(block => {
+ .map((block) => {
const dependency =
/** @type {ContextElementDependency} */
(block.dependencies[0]);
@@ -966,7 +967,7 @@ module.exports = webpackAsyncContext;`;
chunks: undefined
};
})
- .filter(item => item.module);
+ .filter((item) => item.module);
for (const item of items) {
const chunkGroup = chunkGraph.getBlockChunkGroup(item.block);
const chunks = (chunkGroup && chunkGroup.chunks) || [];
@@ -1000,7 +1001,7 @@ module.exports = webpackAsyncContext;`;
map[item.userRequest] = [
...arrayStart,
.../** @type {Chunk[]} */
- (item.chunks).map(chunk => /** @type {ChunkId} */ (chunk.id))
+ (item.chunks).map((chunk) => /** @type {ChunkId} */ (chunk.id))
];
}
}
diff --git a/lib/ContextModuleFactory.js b/lib/ContextModuleFactory.js
index 77a7bf5919c..03e9b3e3a2d 100644
--- a/lib/ContextModuleFactory.js
+++ b/lib/ContextModuleFactory.js
@@ -56,7 +56,7 @@ module.exports = class ContextModuleFactory extends ModuleFactory {
{
name: "alternatives",
/** @type {AsyncSeriesWaterfallHook<[ContextAlternativeRequest[]]>["intercept"]} */
- intercept: interceptor => {
+ intercept: (interceptor) => {
throw new Error(
"Intercepting fake hook ContextModuleFactory.hooks.alternatives is not possible, use ContextModuleFactory.hooks.alternativeRequests instead"
);
@@ -169,13 +169,13 @@ module.exports = class ContextModuleFactory extends ModuleFactory {
asyncLib.parallel(
[
- callback => {
+ (callback) => {
const results = /** @type ResolveRequest[] */ ([]);
/**
* @param {ResolveRequest} obj obj
* @returns {void}
*/
- const yield_ = obj => {
+ const yield_ = (obj) => {
results.push(obj);
};
@@ -189,13 +189,13 @@ module.exports = class ContextModuleFactory extends ModuleFactory {
contextDependencies,
yield: yield_
},
- err => {
+ (err) => {
if (err) return callback(err);
callback(null, results);
}
);
},
- callback => {
+ (callback) => {
asyncLib.map(
loaders,
(loader, callback) => {
@@ -230,7 +230,7 @@ module.exports = class ContextModuleFactory extends ModuleFactory {
/** @type {[ResolveRequest[], string[]]} */ (result);
if (contextResult.length > 1) {
const first = contextResult[0];
- contextResult = contextResult.filter(r => r.path);
+ contextResult = contextResult.filter((r) => r.path);
if (contextResult.length === 0) contextResult.push(first);
}
this.hooks.afterResolve.callAsync(
@@ -241,7 +241,7 @@ module.exports = class ContextModuleFactory extends ModuleFactory {
(loaderResult.length > 0 ? "!" : ""),
resource:
contextResult.length > 1
- ? contextResult.map(r => r.path)
+ ? contextResult.map((r) => r.path)
: contextResult[0].path,
resolveDependencies: this.resolveDependencies.bind(this),
resourceQuery: contextResult[0].query,
@@ -342,13 +342,13 @@ module.exports = class ContextModuleFactory extends ModuleFactory {
fs.readdir(directory, (err, files) => {
if (err) return callback(err);
const processedFiles = cmf.hooks.contextModuleFiles.call(
- /** @type {string[]} */ (files).map(file => file.normalize("NFC"))
+ /** @type {string[]} */ (files).map((file) => file.normalize("NFC"))
);
if (!processedFiles || processedFiles.length === 0) {
return callback(null, []);
}
asyncLib.map(
- processedFiles.filter(p => p.indexOf(".") !== 0),
+ processedFiles.filter((p) => p.indexOf(".") !== 0),
(segment, callback) => {
const subResource = join(fs, directory, segment);
@@ -387,10 +387,10 @@ module.exports = class ContextModuleFactory extends ModuleFactory {
null,
/** @type {ContextAlternativeRequest[]} */
(alternatives)
- .filter(obj =>
+ .filter((obj) =>
regExp.test(/** @type {string} */ (obj.request))
)
- .map(obj => {
+ .map((obj) => {
const dep = new ContextElementDependency(
`${obj.request}${resourceQuery}${resourceFragment}`,
obj.request,
diff --git a/lib/ContextReplacementPlugin.js b/lib/ContextReplacementPlugin.js
index 828b8192ed8..76188c29cd1 100644
--- a/lib/ContextReplacementPlugin.js
+++ b/lib/ContextReplacementPlugin.js
@@ -97,8 +97,8 @@ class ContextReplacementPlugin {
const newContentRegExp = this.newContentRegExp;
const newContentCreateContextMap = this.newContentCreateContextMap;
- compiler.hooks.contextModuleFactory.tap(PLUGIN_NAME, cmf => {
- cmf.hooks.beforeResolve.tap(PLUGIN_NAME, result => {
+ compiler.hooks.contextModuleFactory.tap(PLUGIN_NAME, (cmf) => {
+ cmf.hooks.beforeResolve.tap(PLUGIN_NAME, (result) => {
if (!result) return;
if (resourceRegExp.test(result.request)) {
if (newContentResource !== undefined) {
@@ -120,7 +120,7 @@ class ContextReplacementPlugin {
}
return result;
});
- cmf.hooks.afterResolve.tap(PLUGIN_NAME, result => {
+ cmf.hooks.afterResolve.tap(PLUGIN_NAME, (result) => {
if (!result) return;
if (resourceRegExp.test(result.resource)) {
if (newContentResource !== undefined) {
@@ -183,11 +183,11 @@ class ContextReplacementPlugin {
* @returns {(fs: InputFileSystem, options: ContextModuleOptions, callback: (err: null | Error, dependencies?: ContextElementDependency[]) => void) => void} resolve resolve dependencies from context map function
*/
const createResolveDependenciesFromContextMap =
- createContextMap => (fs, options, callback) => {
+ (createContextMap) => (fs, options, callback) => {
createContextMap(fs, (err, map) => {
if (err) return callback(err);
const dependencies = Object.keys(map).map(
- key =>
+ (key) =>
new ContextElementDependency(
map[key] + options.resourceQuery + options.resourceFragment,
key,
diff --git a/lib/DefinePlugin.js b/lib/DefinePlugin.js
index f60d68f00c9..e3d75973f82 100644
--- a/lib/DefinePlugin.js
+++ b/lib/DefinePlugin.js
@@ -130,7 +130,7 @@ class RuntimeValue {
*/
function getObjKeys(properties) {
if (!properties) return;
- return new Set([...properties].map(p => p.id));
+ return new Set([...properties].map((p) => p.id));
}
/** @typedef {Set | null} ObjKeys */
@@ -161,7 +161,7 @@ const stringifyObj = (
const arr = Array.isArray(obj);
if (arr) {
code = `[${obj
- .map(code =>
+ .map((code) =>
toCode(
code,
parser,
@@ -176,10 +176,10 @@ const stringifyObj = (
} else {
let keys = Object.keys(obj);
if (objKeys) {
- keys = objKeys.size === 0 ? [] : keys.filter(k => objKeys.has(k));
+ keys = objKeys.size === 0 ? [] : keys.filter((k) => objKeys.has(k));
}
code = `{${keys
- .map(key => {
+ .map((key) => {
const code = obj[key];
return `${JSON.stringify(key)}:${toCode(
code,
@@ -286,7 +286,7 @@ const toCode = (
* @param {CodeValue} code code
* @returns {string | undefined} result
*/
-const toCacheVersion = code => {
+const toCacheVersion = (code) => {
if (code === null) {
return "null";
}
@@ -306,7 +306,7 @@ const toCacheVersion = code => {
return `(${code.toString()})`;
}
if (typeof code === "object") {
- const items = Object.keys(code).map(key => ({
+ const items = Object.keys(code).map((key) => ({
key,
value: toCacheVersion(
/** @type {Record} */
@@ -390,7 +390,7 @@ class DefinePlugin {
* @param {JavascriptParser} parser Parser
* @returns {void}
*/
- const handler = parser => {
+ const handler = (parser) => {
const hooked = new Set();
const mainValue =
/** @type {ValueCacheVersion} */
@@ -408,7 +408,7 @@ class DefinePlugin {
/**
* @param {string} key key
*/
- const addValueDependency = key => {
+ const addValueDependency = (key) => {
const buildInfo =
/** @type {BuildInfo} */
(parser.state.module.buildInfo);
@@ -495,7 +495,7 @@ class DefinePlugin {
// why 100? Ensures it runs after object define
stage: 100
},
- expr => {
+ (expr) => {
const destructed =
parser.destructuringAssignmentPropertiesFor(expr);
if (destructed === undefined) {
@@ -557,7 +557,7 @@ class DefinePlugin {
});
parser.hooks.evaluateIdentifier
.for(key)
- .tap(PLUGIN_NAME, expr => {
+ .tap(PLUGIN_NAME, (expr) => {
/**
* this is needed in case there is a recursion in the DefinePlugin
* to prevent an endless recursion
@@ -584,7 +584,7 @@ class DefinePlugin {
res.setRange(/** @type {Range} */ (expr.range));
return res;
});
- parser.hooks.expression.for(key).tap(PLUGIN_NAME, expr => {
+ parser.hooks.expression.for(key).tap(PLUGIN_NAME, (expr) => {
addValueDependency(originalKey);
let strCode = toCode(
code,
@@ -613,7 +613,7 @@ class DefinePlugin {
return toConstantDependency(parser, strCode)(expr);
});
}
- parser.hooks.evaluateTypeof.for(key).tap(PLUGIN_NAME, expr => {
+ parser.hooks.evaluateTypeof.for(key).tap(PLUGIN_NAME, (expr) => {
/**
* this is needed in case there is a recursion in the DefinePlugin
* to prevent an endless recursion
@@ -640,7 +640,7 @@ class DefinePlugin {
res.setRange(/** @type {Range} */ (expr.range));
return res;
});
- parser.hooks.typeof.for(key).tap(PLUGIN_NAME, expr => {
+ parser.hooks.typeof.for(key).tap(PLUGIN_NAME, (expr) => {
addValueDependency(originalKey);
const codeCode = toCode(
code,
@@ -672,20 +672,22 @@ class DefinePlugin {
addValueDependency(key);
return true;
});
- parser.hooks.evaluateIdentifier.for(key).tap(PLUGIN_NAME, expr => {
- addValueDependency(key);
- return new BasicEvaluatedExpression()
- .setTruthy()
- .setSideEffects(false)
- .setRange(/** @type {Range} */ (expr.range));
- });
+ parser.hooks.evaluateIdentifier
+ .for(key)
+ .tap(PLUGIN_NAME, (expr) => {
+ addValueDependency(key);
+ return new BasicEvaluatedExpression()
+ .setTruthy()
+ .setSideEffects(false)
+ .setRange(/** @type {Range} */ (expr.range));
+ });
parser.hooks.evaluateTypeof
.for(key)
.tap(
PLUGIN_NAME,
withValueDependency(key, evaluateToString("object"))
);
- parser.hooks.expression.for(key).tap(PLUGIN_NAME, expr => {
+ parser.hooks.expression.for(key).tap(PLUGIN_NAME, (expr) => {
addValueDependency(key);
let strCode = stringifyObj(
obj,
@@ -778,7 +780,7 @@ class DefinePlugin {
* @param {Record} definitions Definitions map
* @returns {void}
*/
- const walkDefinitionsForKeys = definitions => {
+ const walkDefinitionsForKeys = (definitions) => {
/**
* @param {Map>} map Map
* @param {string} key key
diff --git a/lib/DelegatedModuleFactoryPlugin.js b/lib/DelegatedModuleFactoryPlugin.js
index c12c27bd9d2..32d80a005b1 100644
--- a/lib/DelegatedModuleFactoryPlugin.js
+++ b/lib/DelegatedModuleFactoryPlugin.js
@@ -92,7 +92,7 @@ class DelegatedModuleFactoryPlugin {
}
);
} else {
- normalModuleFactory.hooks.module.tap(PLUGIN_NAME, module => {
+ normalModuleFactory.hooks.module.tap(PLUGIN_NAME, (module) => {
const request = module.libIdent(this.options);
if (request && request in this.options.content) {
const resolved = this.options.content[request];
diff --git a/lib/DllEntryPlugin.js b/lib/DllEntryPlugin.js
index 3bbafb0c645..a63946cf96b 100644
--- a/lib/DllEntryPlugin.js
+++ b/lib/DllEntryPlugin.js
@@ -64,7 +64,7 @@ class DllEntryPlugin {
this.options.name
),
this.options,
- error => {
+ (error) => {
if (error) return callback(error);
callback();
}
diff --git a/lib/DllReferencePlugin.js b/lib/DllReferencePlugin.js
index 0cec5bdcf62..927feb5704b 100644
--- a/lib/DllReferencePlugin.js
+++ b/lib/DllReferencePlugin.js
@@ -102,7 +102,7 @@ class DllReferencePlugin {
return callback();
});
- compiler.hooks.compile.tap(PLUGIN_NAME, params => {
+ compiler.hooks.compile.tap(PLUGIN_NAME, (params) => {
let name = this.options.name;
let sourceType = this.options.sourceType;
let resolvedContent =
diff --git a/lib/DynamicEntryPlugin.js b/lib/DynamicEntryPlugin.js
index 79600542090..d30acbae10a 100644
--- a/lib/DynamicEntryPlugin.js
+++ b/lib/DynamicEntryPlugin.js
@@ -43,9 +43,9 @@ class DynamicEntryPlugin {
}
);
- compiler.hooks.make.tapPromise(PLUGIN_NAME, compilation =>
+ compiler.hooks.make.tapPromise(PLUGIN_NAME, (compilation) =>
Promise.resolve(this.entry())
- .then(entry => {
+ .then((entry) => {
const promises = [];
for (const name of Object.keys(entry)) {
const desc = entry[name];
@@ -68,7 +68,7 @@ class DynamicEntryPlugin {
this.context,
EntryPlugin.createDependency(entry, options),
options,
- err => {
+ (err) => {
if (err) return reject(err);
resolve();
}
diff --git a/lib/EntryPlugin.js b/lib/EntryPlugin.js
index 5031b6d077a..35392d871ba 100644
--- a/lib/EntryPlugin.js
+++ b/lib/EntryPlugin.js
@@ -45,7 +45,7 @@ class EntryPlugin {
const dep = EntryPlugin.createDependency(entry, options);
compiler.hooks.make.tapAsync(PLUGIN_NAME, (compilation, callback) => {
- compilation.addEntry(context, dep, options, err => {
+ compilation.addEntry(context, dep, options, (err) => {
callback(err);
});
});
diff --git a/lib/EnvironmentPlugin.js b/lib/EnvironmentPlugin.js
index 078cdf67c70..3bf01f09673 100644
--- a/lib/EnvironmentPlugin.js
+++ b/lib/EnvironmentPlugin.js
@@ -48,7 +48,7 @@ class EnvironmentPlugin {
: this.defaultValues[key];
if (value === undefined) {
- compiler.hooks.thisCompilation.tap(PLUGIN_NAME, compilation => {
+ compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {
const error = new WebpackError(
`${PLUGIN_NAME} - ${key} environment variable is undefined.\n\n` +
"You can pass an object with default values to suppress this warning.\n" +
diff --git a/lib/ErrorHelpers.js b/lib/ErrorHelpers.js
index af5801786bd..b23d1f1b421 100644
--- a/lib/ErrorHelpers.js
+++ b/lib/ErrorHelpers.js
@@ -28,13 +28,13 @@ const cutOffByFlag = (stack, flag) => {
* @param {string} stack stack trace
* @returns {string} stack trace without the loader execution flag included
*/
-const cutOffLoaderExecution = stack => cutOffByFlag(stack, loaderFlag);
+const cutOffLoaderExecution = (stack) => cutOffByFlag(stack, loaderFlag);
/**
* @param {string} stack stack trace
* @returns {string} stack trace without the webpack options flag included
*/
-const cutOffWebpackOptions = stack => cutOffByFlag(stack, webpackOptionsFlag);
+const cutOffWebpackOptions = (stack) => cutOffByFlag(stack, webpackOptionsFlag);
/**
* @param {string} stack stack trace
diff --git a/lib/EvalDevToolModulePlugin.js b/lib/EvalDevToolModulePlugin.js
index bde4bb6466d..f5ca3d1958b 100644
--- a/lib/EvalDevToolModulePlugin.js
+++ b/lib/EvalDevToolModulePlugin.js
@@ -55,7 +55,7 @@ class EvalDevToolModulePlugin {
* @returns {void}
*/
apply(compiler) {
- compiler.hooks.compilation.tap(PLUGIN_NAME, compilation => {
+ compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
const hooks = JavascriptModulesPlugin.getCompilationHooks(compilation);
hooks.renderModuleContent.tap(
PLUGIN_NAME,
@@ -110,7 +110,7 @@ class EvalDevToolModulePlugin {
);
hooks.render.tap(
PLUGIN_NAME,
- source => new ConcatSource(devtoolWarning, source)
+ (source) => new ConcatSource(devtoolWarning, source)
);
hooks.chunkHash.tap(PLUGIN_NAME, (chunk, hash) => {
hash.update(PLUGIN_NAME);
diff --git a/lib/EvalSourceMapDevToolPlugin.js b/lib/EvalSourceMapDevToolPlugin.js
index 386f8ae4f80..a8c6ce318d4 100644
--- a/lib/EvalSourceMapDevToolPlugin.js
+++ b/lib/EvalSourceMapDevToolPlugin.js
@@ -69,7 +69,7 @@ class EvalSourceMapDevToolPlugin {
*/
apply(compiler) {
const options = this.options;
- compiler.hooks.compilation.tap(PLUGIN_NAME, compilation => {
+ compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
const hooks = JavascriptModulesPlugin.getCompilationHooks(compilation);
new SourceMapDevToolModuleOptionsPlugin(options).apply(compilation);
const matchModule = ModuleFilenameHelpers.matchObject.bind(
@@ -88,7 +88,7 @@ class EvalSourceMapDevToolPlugin {
* @param {Source} r result
* @returns {Source} result
*/
- const result = r => {
+ const result = (r) => {
cache.set(source, r);
return r;
};
@@ -136,13 +136,13 @@ class EvalSourceMapDevToolPlugin {
sourceMap = { ...sourceMap };
const context = /** @type {string} */ (compiler.options.context);
const root = compiler.root;
- const modules = sourceMap.sources.map(source => {
+ const modules = sourceMap.sources.map((source) => {
if (!source.startsWith("webpack://")) return source;
source = makePathsAbsolute(context, source.slice(10), root);
const module = compilation.findModule(source);
return module || source;
});
- let moduleFilenames = modules.map(module =>
+ let moduleFilenames = modules.map((module) =>
ModuleFilenameHelpers.createFilename(
module,
{
@@ -205,7 +205,7 @@ class EvalSourceMapDevToolPlugin {
);
hooks.render.tap(
PLUGIN_NAME,
- source => new ConcatSource(devtoolWarning, source)
+ (source) => new ConcatSource(devtoolWarning, source)
);
hooks.chunkHash.tap(PLUGIN_NAME, (chunk, hash) => {
hash.update(PLUGIN_NAME);
diff --git a/lib/ExportsInfo.js b/lib/ExportsInfo.js
index e8fb81d01d0..695511ba8f6 100644
--- a/lib/ExportsInfo.js
+++ b/lib/ExportsInfo.js
@@ -142,7 +142,7 @@ class ExportsInfo {
if (this._redirectTo !== undefined) {
/** @type {Exports} */
const map = new Map(
- Array.from(this._redirectTo.orderedExports, item => [item.name, item])
+ Array.from(this._redirectTo.orderedExports, (item) => [item.name, item])
);
for (const [key, value] of this._exports) {
map.set(key, value);
@@ -402,7 +402,7 @@ class ExportsInfo {
} else {
if (
this._otherExportsInfo.setUsedConditionally(
- used => used < UsageState.Unknown,
+ (used) => used < UsageState.Unknown,
UsageState.Unknown,
runtime
)
@@ -465,7 +465,7 @@ class ExportsInfo {
*/
setUsedForSideEffectsOnly(runtime) {
return this._sideEffectsOnlyInfo.setUsedConditionally(
- used => used === UsageState.Unused,
+ (used) => used === UsageState.Unused,
UsageState.Used,
runtime
);
@@ -988,7 +988,7 @@ class ExportInfo {
let changed = false;
if (
this.setUsedConditionally(
- used => used < UsageState.Unknown,
+ (used) => used < UsageState.Unknown,
UsageState.Unknown,
runtime
)
@@ -1050,7 +1050,7 @@ class ExportInfo {
} else if (this._usedInRuntime === undefined) {
if (newValue !== UsageState.Unused && condition(UsageState.Unused)) {
this._usedInRuntime = new Map();
- forEachRuntime(runtime, runtime =>
+ forEachRuntime(runtime, (runtime) =>
/** @type {UsedInRuntime} */
(this._usedInRuntime).set(/** @type {string} */ (runtime), newValue)
);
@@ -1058,7 +1058,7 @@ class ExportInfo {
}
} else {
let changed = false;
- forEachRuntime(runtime, _runtime => {
+ forEachRuntime(runtime, (_runtime) => {
const runtime = /** @type {string} */ (_runtime);
const usedInRuntime =
/** @type {UsedInRuntime} */
@@ -1098,7 +1098,7 @@ class ExportInfo {
} else if (this._usedInRuntime === undefined) {
if (newValue !== UsageState.Unused) {
this._usedInRuntime = new Map();
- forEachRuntime(runtime, runtime =>
+ forEachRuntime(runtime, (runtime) =>
/** @type {UsedInRuntime} */
(this._usedInRuntime).set(/** @type {string} */ (runtime), newValue)
);
@@ -1106,7 +1106,7 @@ class ExportInfo {
}
} else {
let changed = false;
- forEachRuntime(runtime, _runtime => {
+ forEachRuntime(runtime, (_runtime) => {
const runtime = /** @type {string} */ (_runtime);
const usedInRuntime =
/** @type {UsedInRuntime} */
@@ -1247,7 +1247,7 @@ class ExportInfo {
} else if (
runtime !== undefined &&
[...runtime].every(
- runtime =>
+ (runtime) =>
!(/** @type {UsedInRuntime} */ (this._usedInRuntime).has(runtime))
)
) {
diff --git a/lib/ExportsInfoApiPlugin.js b/lib/ExportsInfoApiPlugin.js
index faf4594bbd0..2fdf8bdbecd 100644
--- a/lib/ExportsInfoApiPlugin.js
+++ b/lib/ExportsInfoApiPlugin.js
@@ -38,7 +38,7 @@ class ExportsInfoApiPlugin {
* @param {JavascriptParser} parser the parser
* @returns {void}
*/
- const handler = parser => {
+ const handler = (parser) => {
parser.hooks.expressionMemberChain
.for("__webpack_exports_info__")
.tap(PLUGIN_NAME, (expr, members) => {
@@ -60,7 +60,7 @@ class ExportsInfoApiPlugin {
});
parser.hooks.expression
.for("__webpack_exports_info__")
- .tap(PLUGIN_NAME, expr => {
+ .tap(PLUGIN_NAME, (expr) => {
const dep = new ConstDependency(
"true",
/** @type {Range} */ (expr.range)
diff --git a/lib/ExternalModule.js b/lib/ExternalModule.js
index 66edc91de99..de7b38919fe 100644
--- a/lib/ExternalModule.js
+++ b/lib/ExternalModule.js
@@ -75,8 +75,11 @@ const { register } = require("./util/serialization");
* @property {string} expression
* @property {InitFragment[]=} chunkInitFragments
* @property {ReadOnlyRuntimeRequirements=} runtimeRequirements
+ * @property {[string, string][]=} specifiers
*/
+/** @typedef {true | [string, string][]} Imported */
+
const RUNTIME_REQUIREMENTS = new Set([RuntimeGlobals.module]);
const RUNTIME_REQUIREMENTS_FOR_SCRIPT = new Set([RuntimeGlobals.loadScript]);
const RUNTIME_REQUIREMENTS_FOR_MODULE = new Set([
@@ -96,7 +99,9 @@ const getSourceForGlobalVariableExternal = (variableName, type) => {
}
// needed for e.g. window["some"]["thing"]
- const objectLookup = variableName.map(r => `[${JSON.stringify(r)}]`).join("");
+ const objectLookup = variableName
+ .map((r) => `[${JSON.stringify(r)}]`)
+ .join("");
return {
iife: type === "this",
expression: `${type}${objectLookup}`
@@ -107,7 +112,7 @@ const getSourceForGlobalVariableExternal = (variableName, type) => {
* @param {string|string[]} moduleAndSpecifiers the module request
* @returns {SourceData} the generated source
*/
-const getSourceForCommonJsExternal = moduleAndSpecifiers => {
+const getSourceForCommonJsExternal = (moduleAndSpecifiers) => {
if (!Array.isArray(moduleAndSpecifiers)) {
return {
expression: `require(${JSON.stringify(moduleAndSpecifiers)})`
@@ -123,21 +128,24 @@ const getSourceForCommonJsExternal = moduleAndSpecifiers => {
};
/**
- * @param {string|string[]} moduleAndSpecifiers the module request
- * @param {string} importMetaName import.meta name
- * @param {boolean} needPrefix need to use `node:` prefix for `module` import
+ * @param {string | string[]} moduleAndSpecifiers the module request
+ * @param {RuntimeTemplate} runtimeTemplate the runtime template
* @returns {SourceData} the generated source
*/
const getSourceForCommonJsExternalInNodeModule = (
moduleAndSpecifiers,
- importMetaName,
- needPrefix
+ runtimeTemplate
) => {
+ const importMetaName =
+ /** @type {string} */
+ (runtimeTemplate.outputOptions.importMetaName);
+
+ // /** @type {boolean} */
+ // (runtimeTemplate.supportNodePrefixForCoreModules())
+
const chunkInitFragments = [
new InitFragment(
- `import { createRequire as __WEBPACK_EXTERNAL_createRequire } from "${
- needPrefix ? "node:" : ""
- }module";\n`,
+ `import { createRequire as __WEBPACK_EXTERNAL_createRequire } from ${runtimeTemplate.renderNodePrefixForCoreModule("module")};\n`,
InitFragment.STAGE_HARMONY_IMPORTS,
0,
"external module node-commonjs"
@@ -215,10 +223,9 @@ const getSourceForImportExternal = (
};
/**
- * @template {{ [key: string]: string }} T
- * @param {keyof T} key key
- * @param {T[keyof T]} value value
- * @returns {undefined | T[keyof T]} replaced value
+ * @param {string} key key
+ * @param {ImportAttributes | string | boolean | undefined} value value
+ * @returns {ImportAttributes | string | boolean | undefined} replaced value
*/
const importAssertionReplacer = (key, value) => {
if (key === "_isLegacyAssert") {
@@ -229,17 +236,19 @@ const importAssertionReplacer = (key, value) => {
};
/**
- * @extends {InitFragment}
+ * @extends {InitFragment}
*/
class ModuleExternalInitFragment extends InitFragment {
/**
* @param {string} request import source
+ * @param {Imported} imported the imported specifiers
* @param {string=} ident recomputed ident
* @param {ImportDependencyMeta=} dependencyMeta the dependency meta
* @param {HashFunction=} hashFunction the hash function to use
*/
constructor(
request,
+ imported,
ident,
dependencyMeta,
hashFunction = DEFAULTS.HASH_FUNCTION
@@ -253,28 +262,78 @@ class ModuleExternalInitFragment extends InitFragment {
.slice(0, 8)}`;
}
}
+
const identifier = `__WEBPACK_EXTERNAL_MODULE_${ident}__`;
super(
- `import * as ${identifier} from ${JSON.stringify(request)}${
- dependencyMeta && dependencyMeta.attributes
- ? dependencyMeta.attributes._isLegacyAssert
- ? ` assert ${JSON.stringify(
- dependencyMeta.attributes,
- importAssertionReplacer
- )}`
- : ` with ${JSON.stringify(dependencyMeta.attributes)}`
- : ""
- };\n`,
+ "",
InitFragment.STAGE_HARMONY_IMPORTS,
0,
- `external module import ${ident}`
+ `external module import ${ident} ${imported === true ? imported : imported.join(" ")}`
);
this._ident = ident;
this._request = request;
- this._dependencyMeta = request;
+ this._dependencyMeta = dependencyMeta;
+ this._imported = imported;
this._identifier = identifier;
}
+ /**
+ * @returns {Imported} imported
+ */
+ getImported() {
+ return this._imported;
+ }
+
+ /**
+ * @param {Imported} imported imported
+ */
+ setImported(imported) {
+ this._imported = imported;
+ }
+
+ /**
+ * @param {GenerateContext} context context
+ * @returns {string | Source | undefined} the source code that will be included as initialization code
+ */
+ getContent(context) {
+ const {
+ _dependencyMeta: dependencyMeta,
+ _imported: imported,
+ _request: request,
+ _identifier: identifier
+ } = this;
+ const attributes =
+ dependencyMeta && dependencyMeta.attributes
+ ? dependencyMeta.attributes._isLegacyAssert &&
+ dependencyMeta.attributes._isLegacyAssert
+ ? ` assert ${JSON.stringify(
+ dependencyMeta.attributes,
+ importAssertionReplacer
+ )}`
+ : ` with ${JSON.stringify(dependencyMeta.attributes)}`
+ : "";
+ let content = "";
+ if (imported === true) {
+ // namespace
+ content = `import * as ${identifier} from ${JSON.stringify(request)}${
+ attributes
+ };\n`;
+ } else if (imported.length === 0) {
+ // just import, no use
+ content = `import ${JSON.stringify(request)}${attributes};\n`;
+ } else {
+ content = `import { ${imported
+ .map(([name, finalName]) => {
+ if (name !== finalName) {
+ return `${name} as ${finalName}`;
+ }
+ return name;
+ })
+ .join(", ")} } from ${JSON.stringify(request)}${attributes};\n`;
+ }
+ return content;
+ }
+
getNamespaceIdentifier() {
return this._identifier;
}
@@ -287,11 +346,12 @@ register(
{
serialize(obj, { write }) {
write(obj._request);
+ write(obj._imported);
write(obj._ident);
write(obj._dependencyMeta);
},
deserialize({ read }) {
- return new ModuleExternalInitFragment(read(), read(), read());
+ return new ModuleExternalInitFragment(read(), read(), read(), read());
}
}
);
@@ -343,6 +403,7 @@ const generateModuleRemapping = (
* @param {RuntimeSpec} runtime the runtime
* @param {RuntimeTemplate} runtimeTemplate the runtime template
* @param {ImportDependencyMeta} dependencyMeta the dependency meta
+ * @param {ConcatenationScope=} concatenationScope concatenationScope
* @returns {SourceData} the generated source
*/
const getSourceForModuleExternal = (
@@ -350,28 +411,71 @@ const getSourceForModuleExternal = (
exportsInfo,
runtime,
runtimeTemplate,
- dependencyMeta
+ dependencyMeta,
+ concatenationScope
) => {
if (!Array.isArray(moduleAndSpecifiers)) {
moduleAndSpecifiers = [moduleAndSpecifiers];
}
+
+ /** @type {Imported} */
+ let imported = true;
+ if (concatenationScope) {
+ const usedExports = exportsInfo.getUsedExports(runtime);
+ switch (usedExports) {
+ case true:
+ case null:
+ // unknown exports
+ imported = true;
+ break;
+ case false:
+ // no used exports
+ imported = [];
+ break;
+ default:
+ imported = [];
+ if (exportsInfo.isUsed(runtime) === false) {
+ // no used, only
+ }
+ for (const [name] of usedExports.entries()) {
+ let counter = 0;
+ let finalName = name;
+
+ if (concatenationScope) {
+ while (!concatenationScope.registerUsedName(finalName)) {
+ finalName = `${name}_${counter++}`;
+ }
+ }
+ imported.push([name, finalName]);
+ }
+ }
+ }
+
const initFragment = new ModuleExternalInitFragment(
moduleAndSpecifiers[0],
+ imported,
undefined,
dependencyMeta,
runtimeTemplate.outputOptions.hashFunction
);
+ const specifiers = imported === true ? undefined : imported;
const baseAccess = `${initFragment.getNamespaceIdentifier()}${propertyAccess(
moduleAndSpecifiers,
1
)}`;
- const moduleRemapping = generateModuleRemapping(
- baseAccess,
- exportsInfo,
- runtime,
- runtimeTemplate
- );
- const expression = moduleRemapping || baseAccess;
+ let expression = baseAccess;
+
+ const useNamespace = imported === true;
+ let moduleRemapping;
+ if (useNamespace) {
+ moduleRemapping = generateModuleRemapping(
+ baseAccess,
+ exportsInfo,
+ runtime,
+ runtimeTemplate
+ );
+ expression = moduleRemapping || baseAccess;
+ }
return {
expression,
init: moduleRemapping
@@ -383,10 +487,13 @@ const getSourceForModuleExternal = (
"x"
)}`
: undefined,
+ specifiers,
runtimeRequirements: moduleRemapping
? RUNTIME_REQUIREMENTS_FOR_MODULE
: undefined,
- chunkInitFragments: [initFragment]
+ chunkInitFragments: [
+ /** @type {InitFragment} */ (initFragment)
+ ]
};
};
@@ -733,6 +840,7 @@ class ExternalModule extends Module {
* @param {ChunkGraph} chunkGraph the chunk graph
* @param {RuntimeSpec} runtime the runtime
* @param {DependencyMeta | undefined} dependencyMeta the dependency meta
+ * @param {ConcatenationScope=} concatenationScope concatenationScope
* @returns {SourceData} the source data
*/
_getSourceData(
@@ -742,7 +850,8 @@ class ExternalModule extends Module {
moduleGraph,
chunkGraph,
runtime,
- dependencyMeta
+ dependencyMeta,
+ concatenationScope
) {
switch (externalType) {
case "this":
@@ -761,13 +870,7 @@ class ExternalModule extends Module {
return getSourceForCommonJsExternal(request);
case "node-commonjs":
return /** @type {BuildInfo} */ (this.buildInfo).javascriptModule
- ? getSourceForCommonJsExternalInNodeModule(
- request,
- /** @type {string} */
- (runtimeTemplate.outputOptions.importMetaName),
- /** @type {boolean} */
- (runtimeTemplate.supportNodePrefixForCoreModules())
- )
+ ? getSourceForCommonJsExternalInNodeModule(request, runtimeTemplate)
: getSourceForCommonJsExternal(request);
case "amd":
case "amd-require":
@@ -818,7 +921,8 @@ class ExternalModule extends Module {
moduleGraph.getExportsInfo(this),
runtime,
runtimeTemplate,
- /** @type {ImportDependencyMeta} */ (dependencyMeta)
+ /** @type {ImportDependencyMeta} */ (dependencyMeta),
+ concatenationScope
);
}
case "var":
@@ -898,14 +1002,24 @@ class ExternalModule extends Module {
moduleGraph,
chunkGraph,
runtime,
- this.dependencyMeta
+ this.dependencyMeta,
+ concatenationScope
);
+ // sourceString can be empty str only when there is concatenationScope
let sourceString = sourceData.expression;
if (sourceData.iife) {
sourceString = `(function() { return ${sourceString}; }())`;
}
- if (concatenationScope) {
+
+ const specifiers = sourceData.specifiers;
+ if (specifiers) {
+ sourceString = "";
+ const scope = /** @type {ConcatenationScope} */ (concatenationScope);
+ for (const [specifier, finalName] of specifiers) {
+ scope.registerRawExport(specifier, finalName);
+ }
+ } else if (concatenationScope) {
sourceString = `${
runtimeTemplate.supportsConst() ? "const" : "var"
} ${ConcatenationScope.NAMESPACE_OBJECT_EXPORT} = ${sourceString};`;
@@ -1011,3 +1125,4 @@ class ExternalModule extends Module {
makeSerializable(ExternalModule, "webpack/lib/ExternalModule");
module.exports = ExternalModule;
+module.exports.ModuleExternalInitFragment = ModuleExternalInitFragment;
diff --git a/lib/ExternalModuleFactoryPlugin.js b/lib/ExternalModuleFactoryPlugin.js
index 85b95b95d52..e011ae0e9eb 100644
--- a/lib/ExternalModuleFactoryPlugin.js
+++ b/lib/ExternalModuleFactoryPlugin.js
@@ -264,7 +264,7 @@ class ExternalModuleFactoryPlugin {
request: dependency.request,
dependencyType,
contextInfo,
- getResolve: options => (context, request, callback) => {
+ getResolve: (options) => (context, request, callback) => {
const resolveContext = {
fileDependencies: data.fileDependencies,
missingDependencies: data.missingDependencies,
@@ -307,7 +307,7 @@ class ExternalModuleFactoryPlugin {
},
cb
);
- if (promise && promise.then) promise.then(r => cb(null, r), cb);
+ if (promise && promise.then) promise.then((r) => cb(null, r), cb);
}
return;
} else if (typeof externals === "object") {
diff --git a/lib/ExternalsPlugin.js b/lib/ExternalsPlugin.js
index 87b692e7fed..b713357ec3c 100644
--- a/lib/ExternalsPlugin.js
+++ b/lib/ExternalsPlugin.js
@@ -5,10 +5,13 @@
"use strict";
+const { ModuleExternalInitFragment } = require("./ExternalModule");
const ExternalModuleFactoryPlugin = require("./ExternalModuleFactoryPlugin");
+const ConcatenatedModule = require("./optimize/ConcatenatedModule");
/** @typedef {import("../declarations/WebpackOptions").Externals} Externals */
/** @typedef {import("./Compiler")} Compiler */
+/** @typedef {import("./optimize/ConcatenatedModule").ConcatenatedModuleInfo} ConcatenatedModuleInfo */
const PLUGIN_NAME = "ExternalsPlugin";
@@ -33,6 +36,48 @@ class ExternalsPlugin {
normalModuleFactory
);
});
+
+ compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
+ const { concatenatedModuleInfo } =
+ ConcatenatedModule.getCompilationHooks(compilation);
+ concatenatedModuleInfo.tap(PLUGIN_NAME, (updatedInfo, moduleInfo) => {
+ const rawExportMap =
+ /** @type {ConcatenatedModuleInfo} */ updatedInfo.rawExportMap;
+
+ if (!rawExportMap) {
+ return;
+ }
+
+ const chunkInitFragments =
+ /** @type {ConcatenatedModuleInfo} */ moduleInfo.chunkInitFragments;
+ const moduleExternalInitFragments = chunkInitFragments
+ ? chunkInitFragments.filter(
+ (fragment) => fragment instanceof ModuleExternalInitFragment
+ )
+ : [];
+
+ let initFragmentChanged = false;
+
+ for (const fragment of moduleExternalInitFragments) {
+ const imported = fragment.getImported();
+
+ if (Array.isArray(imported)) {
+ const newImported = imported.map(([specifier, finalName]) => [
+ specifier,
+ rawExportMap.has(specifier)
+ ? rawExportMap.get(specifier)
+ : finalName
+ ]);
+ fragment.setImported(newImported);
+ initFragmentChanged = true;
+ }
+ }
+
+ if (initFragmentChanged) {
+ return true;
+ }
+ });
+ });
}
}
diff --git a/lib/FileSystemInfo.js b/lib/FileSystemInfo.js
index f295078b67b..8ae2f7ffc20 100644
--- a/lib/FileSystemInfo.js
+++ b/lib/FileSystemInfo.js
@@ -15,6 +15,7 @@ const StackedCacheMap = require("./util/StackedCacheMap");
const createHash = require("./util/createHash");
const { dirname, join, lstatReadlinkAbsolute, relative } = require("./util/fs");
const makeSerializable = require("./util/makeSerializable");
+const memoize = require("./util/memoize");
const processAsyncTree = require("./util/processAsyncTree");
/** @typedef {import("enhanced-resolve").Resolver} Resolver */
@@ -550,7 +551,7 @@ class Snapshot {
*/
getFileIterable() {
if (this._cachedFileIterable === undefined) {
- this._cachedFileIterable = this._createIterable(s => [
+ this._cachedFileIterable = this._createIterable((s) => [
s.fileTimestamps,
s.fileHashes,
s.fileTshs,
@@ -565,7 +566,7 @@ class Snapshot {
*/
getContextIterable() {
if (this._cachedContextIterable === undefined) {
- this._cachedContextIterable = this._createIterable(s => [
+ this._cachedContextIterable = this._createIterable((s) => [
s.contextTimestamps,
s.contextHashes,
s.contextTshs,
@@ -580,7 +581,7 @@ class Snapshot {
*/
getMissingIterable() {
if (this._cachedMissingIterable === undefined) {
- this._cachedMissingIterable = this._createIterable(s => [
+ this._cachedMissingIterable = this._createIterable((s) => [
s.missingExistence,
s.managedMissing
]);
@@ -661,7 +662,7 @@ class SnapshotOptimization {
* @param {SnapshotOptimizationEntry} entry optimization entry
* @returns {void}
*/
- const increaseSharedAndStoreOptimizationEntry = entry => {
+ const increaseSharedAndStoreOptimizationEntry = (entry) => {
if (entry.children !== undefined) {
for (const child of entry.children) {
increaseSharedAndStoreOptimizationEntry(child);
@@ -674,7 +675,7 @@ class SnapshotOptimization {
* @param {SnapshotOptimizationEntry} entry optimization entry
* @returns {void}
*/
- const storeOptimizationEntry = entry => {
+ const storeOptimizationEntry = (entry) => {
for (const path of /** @type {SnapshotContent} */ (
entry.snapshotContent
)) {
@@ -872,7 +873,7 @@ class SnapshotOptimization {
* @param {string} str input
* @returns {string} result
*/
-const parseString = str => {
+const parseString = (str) => {
if (str[0] === "'" || str[0] === "`") {
str = `"${str.slice(1, -1).replace(/"/g, '\\"')}"`;
}
@@ -883,7 +884,7 @@ const parseString = str => {
/**
* @param {number} mtime mtime
*/
-const applyMtime = mtime => {
+const applyMtime = (mtime) => {
if (FS_ACCURACY > 1 && mtime % 2 !== 0) FS_ACCURACY = 1;
else if (FS_ACCURACY > 10 && mtime % 20 !== 0) FS_ACCURACY = 10;
else if (FS_ACCURACY > 100 && mtime % 200 !== 0) FS_ACCURACY = 100;
@@ -1014,7 +1015,7 @@ const getManagedItem = (managedPath, path) => {
* @param {T | null} entry entry
* @returns {T["resolved"] | null | undefined} the resolved entry
*/
-const getResolvedTimestamp = entry => {
+const getResolvedTimestamp = (entry) => {
if (entry === null) return null;
if (entry.resolved !== undefined) return entry.resolved;
return entry.symlinks === undefined ? entry : undefined;
@@ -1024,7 +1025,7 @@ const getResolvedTimestamp = entry => {
* @param {ContextHash | null} entry entry
* @returns {string | null | undefined} the resolved entry
*/
-const getResolvedHash = entry => {
+const getResolvedHash = (entry) => {
if (entry === null) return null;
if (entry.resolved !== undefined) return entry.resolved;
return entry.symlinks === undefined ? entry.hash : undefined;
@@ -1039,6 +1040,8 @@ const addAll = (source, target) => {
for (const key of source) target.add(key);
};
+const getEsModuleLexer = memoize(() => require("es-module-lexer"));
+
/** @typedef {Set} LoggedPaths */
/** @typedef {FileSystemInfoEntry | "ignore" | null} FileTimestamp */
@@ -1079,66 +1082,66 @@ class FileSystemInfo {
/** @type {WeakMap} */
this._snapshotCache = new WeakMap();
this._fileTimestampsOptimization = new SnapshotOptimization(
- s => s.hasFileTimestamps(),
- s => s.fileTimestamps,
+ (s) => s.hasFileTimestamps(),
+ (s) => s.fileTimestamps,
(s, v) => s.setFileTimestamps(v)
);
this._fileHashesOptimization = new SnapshotOptimization(
- s => s.hasFileHashes(),
- s => s.fileHashes,
+ (s) => s.hasFileHashes(),
+ (s) => s.fileHashes,
(s, v) => s.setFileHashes(v),
false
);
this._fileTshsOptimization = new SnapshotOptimization(
- s => s.hasFileTshs(),
- s => s.fileTshs,
+ (s) => s.hasFileTshs(),
+ (s) => s.fileTshs,
(s, v) => s.setFileTshs(v)
);
this._contextTimestampsOptimization = new SnapshotOptimization(
- s => s.hasContextTimestamps(),
- s => s.contextTimestamps,
+ (s) => s.hasContextTimestamps(),
+ (s) => s.contextTimestamps,
(s, v) => s.setContextTimestamps(v)
);
this._contextHashesOptimization = new SnapshotOptimization(
- s => s.hasContextHashes(),
- s => s.contextHashes,
+ (s) => s.hasContextHashes(),
+ (s) => s.contextHashes,
(s, v) => s.setContextHashes(v),
false
);
this._contextTshsOptimization = new SnapshotOptimization(
- s => s.hasContextTshs(),
- s => s.contextTshs,
+ (s) => s.hasContextTshs(),
+ (s) => s.contextTshs,
(s, v) => s.setContextTshs(v)
);
this._missingExistenceOptimization = new SnapshotOptimization(
- s => s.hasMissingExistence(),
- s => s.missingExistence,
+ (s) => s.hasMissingExistence(),
+ (s) => s.missingExistence,
(s, v) => s.setMissingExistence(v),
false
);
this._managedItemInfoOptimization = new SnapshotOptimization(
- s => s.hasManagedItemInfo(),
- s => s.managedItemInfo,
+ (s) => s.hasManagedItemInfo(),
+ (s) => s.managedItemInfo,
(s, v) => s.setManagedItemInfo(v),
false
);
this._managedFilesOptimization = new SnapshotOptimization(
- s => s.hasManagedFiles(),
- s => s.managedFiles,
+ (s) => s.hasManagedFiles(),
+ (s) => s.managedFiles,
(s, v) => s.setManagedFiles(v),
false,
true
);
this._managedContextsOptimization = new SnapshotOptimization(
- s => s.hasManagedContexts(),
- s => s.managedContexts,
+ (s) => s.hasManagedContexts(),
+ (s) => s.managedContexts,
(s, v) => s.setManagedContexts(v),
false,
true
);
this._managedMissingOptimization = new SnapshotOptimization(
- s => s.hasManagedMissing(),
- s => s.managedMissing,
+ (s) => s.hasManagedMissing(),
+ (s) => s.managedMissing,
(s, v) => s.setManagedMissing(v),
false,
true
@@ -1202,32 +1205,32 @@ class FileSystemInfo {
const _unmanagedPaths = [...unmanagedPaths];
this.unmanagedPathsWithSlash =
/** @type {string[]} */
- (_unmanagedPaths.filter(p => typeof p === "string")).map(p =>
+ (_unmanagedPaths.filter((p) => typeof p === "string")).map((p) =>
join(fs, p, "_").slice(0, -1)
);
this.unmanagedPathsRegExps =
/** @type {RegExp[]} */
- (_unmanagedPaths.filter(p => typeof p !== "string"));
+ (_unmanagedPaths.filter((p) => typeof p !== "string"));
this.managedPaths = [...managedPaths];
this.managedPathsWithSlash =
/** @type {string[]} */
- (this.managedPaths.filter(p => typeof p === "string")).map(p =>
+ (this.managedPaths.filter((p) => typeof p === "string")).map((p) =>
join(fs, p, "_").slice(0, -1)
);
this.managedPathsRegExps =
/** @type {RegExp[]} */
- (this.managedPaths.filter(p => typeof p !== "string"));
+ (this.managedPaths.filter((p) => typeof p !== "string"));
this.immutablePaths = [...immutablePaths];
this.immutablePathsWithSlash =
/** @type {string[]} */
- (this.immutablePaths.filter(p => typeof p === "string")).map(p =>
+ (this.immutablePaths.filter((p) => typeof p === "string")).map((p) =>
join(fs, p, "_").slice(0, -1)
);
this.immutablePathsRegExps =
/** @type {RegExp[]} */
- (this.immutablePaths.filter(p => typeof p !== "string"));
+ (this.immutablePaths.filter((p) => typeof p !== "string"));
this._cachedDeprecatedFileTimestamps = undefined;
this._cachedDeprecatedContextTimestamps = undefined;
@@ -1605,7 +1608,7 @@ class FileSystemInfo {
* @param {undefined | boolean | string} expected expected result
* @returns {string} expected result
*/
- const expectedToString = expected =>
+ const expectedToString = (expected) =>
expected ? ` (expected ${expected})` : "";
/** @typedef {{ type: JobType, context: string | undefined, path: string, issuer: Job | undefined, expected: undefined | boolean | string }} Job */
@@ -1613,7 +1616,7 @@ class FileSystemInfo {
* @param {Job} job job
* @returns {`resolve commonjs file ${string}${string}`|`resolve esm file ${string}${string}`|`resolve esm ${string}${string}`|`resolve directory ${string}`|`file ${string}`|`unknown ${string} ${string}`|`resolve commonjs ${string}${string}`|`directory ${string}`|`file dependencies ${string}`|`directory dependencies ${string}`} result
*/
- const jobToString = job => {
+ const jobToString = (job) => {
switch (job.type) {
case RBDT_RESOLVE_CJS:
return `resolve commonjs ${job.path}${expectedToString(
@@ -1646,7 +1649,7 @@ class FileSystemInfo {
* @param {Job} job job
* @returns {string} string value
*/
- const pathToString = job => {
+ const pathToString = (job) => {
let result = ` at ${jobToString(job)}`;
/** @type {Job | undefined} */
(job) = job.issuer;
@@ -1660,7 +1663,7 @@ class FileSystemInfo {
processAsyncTree(
Array.from(
deps,
- dep =>
+ (dep) =>
/** @type {Job} */ ({
type: RBDT_RESOLVE_CJS,
context,
@@ -1676,7 +1679,7 @@ class FileSystemInfo {
* @param {string} path path
* @returns {void}
*/
- const resolveDirectory = path => {
+ const resolveDirectory = (path) => {
const key = `d\n${context}\n${path}`;
if (resolveResults.has(key)) {
return callback();
@@ -1935,7 +1938,7 @@ class FileSystemInfo {
this._warnAboutExperimentalEsmTracking = true;
}
- const lexer = require("es-module-lexer");
+ const lexer = getEsModuleLexer();
lexer.init.then(() => {
this.fs.readFile(path, (err, content) => {
@@ -2071,7 +2074,7 @@ class FileSystemInfo {
}
}
},
- err => {
+ (err) => {
if (err) return callback(err);
for (const l of fileSymlinks) files.delete(l);
for (const l of directorySymlinks) directories.delete(l);
@@ -2158,7 +2161,7 @@ class FileSystemInfo {
* @param {Error | typeof INVALID=} err error or invalid flag
* @returns {void}
*/
- err => {
+ (err) => {
if (err === INVALID) {
return callback(null, false);
}
@@ -2172,9 +2175,9 @@ class FileSystemInfo {
/**
* @param {number | null | undefined} startTime when processing the files has started
- * @param {Iterable | null} files all files
- * @param {Iterable | null} directories all directories
- * @param {Iterable | null} missing all missing files or directories
+ * @param {Iterable | null | undefined} files all files
+ * @param {Iterable | null | undefined} directories all directories
+ * @param {Iterable | null | undefined} missing all missing files or directories
* @param {SnapshotOptions | null | undefined} options options object (for future extensions)
* @param {(err: WebpackError | null, snapshot: Snapshot | null) => void} callback callback function
* @returns {void}
@@ -2332,7 +2335,7 @@ class FileSystemInfo {
/**
* @param {ManagedFiles} capturedFiles captured files
*/
- const processCapturedFiles = capturedFiles => {
+ const processCapturedFiles = (capturedFiles) => {
switch (mode) {
case 3:
this._fileTshsOptimization.optimize(snapshot, capturedFiles);
@@ -2420,7 +2423,7 @@ class FileSystemInfo {
/**
* @param {ManagedContexts} capturedDirectories captured directories
*/
- const processCapturedDirectories = capturedDirectories => {
+ const processCapturedDirectories = (capturedDirectories) => {
switch (mode) {
case 3:
this._contextTshsOptimization.optimize(snapshot, capturedDirectories);
@@ -2565,7 +2568,7 @@ class FileSystemInfo {
/**
* @param {ManagedMissing} capturedMissing captured missing
*/
- const processCapturedMissing = capturedMissing => {
+ const processCapturedMissing = (capturedMissing) => {
this._missingExistenceOptimization.optimize(snapshot, capturedMissing);
for (const path of capturedMissing) {
const cache = this._fileTimestamps.get(path);
@@ -3345,7 +3348,7 @@ class FileSystemInfo {
* @param {string} hash hash
* @returns {void}
*/
- const continueWithHash = hash => {
+ const continueWithHash = (hash) => {
const cache = this._fileTimestamps.get(path);
if (cache !== undefined) {
if (cache !== "ignore") {
@@ -3421,8 +3424,8 @@ class FileSystemInfo {
return callback(err);
}
const files = /** @type {string[]} */ (_files)
- .map(file => file.normalize("NFC"))
- .filter(file => !/^\./.test(file))
+ .map((file) => file.normalize("NFC"))
+ .filter((file) => !/^\./.test(file))
.sort();
asyncLib.map(
files,
@@ -3510,7 +3513,7 @@ class FileSystemInfo {
fromImmutablePath: () =>
/** @type {ContextFileSystemInfoEntry | FileSystemInfoEntry | "ignore" | null} */
(null),
- fromManagedItem: info => ({
+ fromManagedItem: (info) => ({
safeTime: 0,
timestampHash: info
}),
@@ -3643,7 +3646,7 @@ class FileSystemInfo {
callback();
});
},
- err => {
+ (err) => {
if (err) return callback(/** @type {WebpackError} */ (err));
const hash = createHash(this._hashFunction);
hash.update(/** @type {string} */ (entry.timestampHash));
@@ -3674,7 +3677,7 @@ class FileSystemInfo {
{
path,
fromImmutablePath: () => /** @type {ContextHash | ""} */ (""),
- fromManagedItem: info => info || "",
+ fromManagedItem: (info) => info || "",
fromSymlink: (file, target, callback) => {
callback(
null,
@@ -3759,7 +3762,7 @@ class FileSystemInfo {
callback();
});
},
- err => {
+ (err) => {
if (err) return callback(/** @type {WebpackError} */ (err));
const hash = createHash(this._hashFunction);
hash.update(entry.hash);
@@ -3817,7 +3820,7 @@ class FileSystemInfo {
path,
fromImmutablePath: () =>
/** @type {ContextTimestampAndHash | null} */ (null),
- fromManagedItem: info => ({
+ fromManagedItem: (info) => ({
safeTime: 0,
timestampHash: info,
hash: info || ""
@@ -3937,7 +3940,7 @@ class FileSystemInfo {
callback();
});
},
- err => {
+ (err) => {
if (err) return callback(/** @type {WebpackError} */ (err));
const hash = createHash(this._hashFunction);
const tsHash = createHash(this._hashFunction);
@@ -3979,7 +3982,7 @@ class FileSystemInfo {
return callback(/** @type {WebpackError} */ (err));
}
const set = new Set(
- /** @type {string[]} */ (elements).map(element =>
+ /** @type {string[]} */ (elements).map((element) =>
join(this.fs, path, element)
)
);
diff --git a/lib/FlagAllModulesAsUsedPlugin.js b/lib/FlagAllModulesAsUsedPlugin.js
index eb3ee4cf43d..0f5969cac7a 100644
--- a/lib/FlagAllModulesAsUsedPlugin.js
+++ b/lib/FlagAllModulesAsUsedPlugin.js
@@ -26,9 +26,9 @@ class FlagAllModulesAsUsedPlugin {
* @returns {void}
*/
apply(compiler) {
- compiler.hooks.compilation.tap(PLUGIN_NAME, compilation => {
+ compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
const moduleGraph = compilation.moduleGraph;
- compilation.hooks.optimizeDependencies.tap(PLUGIN_NAME, modules => {
+ compilation.hooks.optimizeDependencies.tap(PLUGIN_NAME, (modules) => {
/** @type {RuntimeSpec} */
let runtime;
for (const [name, { options }] of compilation.entries) {
diff --git a/lib/FlagDependencyExportsPlugin.js b/lib/FlagDependencyExportsPlugin.js
index abb93846c1d..b26e3b03faf 100644
--- a/lib/FlagDependencyExportsPlugin.js
+++ b/lib/FlagDependencyExportsPlugin.js
@@ -28,7 +28,7 @@ class FlagDependencyExportsPlugin {
* @returns {void}
*/
apply(compiler) {
- compiler.hooks.compilation.tap(PLUGIN_NAME, compilation => {
+ compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
const moduleGraph = compilation.moduleGraph;
const cache = compilation.getCache(PLUGIN_NAME);
compilation.hooks.finishModules.tapAsync(
@@ -103,7 +103,7 @@ class FlagDependencyExportsPlugin {
}
);
},
- err => {
+ (err) => {
logger.timeEnd("restore cached provided exports");
if (err) return callback(err);
@@ -129,7 +129,7 @@ class FlagDependencyExportsPlugin {
* @param {DependenciesBlock} depBlock the dependencies block
* @returns {void}
*/
- const processDependenciesBlock = depBlock => {
+ const processDependenciesBlock = (depBlock) => {
for (const dep of depBlock.dependencies) {
processDependency(dep);
}
@@ -142,7 +142,7 @@ class FlagDependencyExportsPlugin {
* @param {Dependency} dep the dependency
* @returns {void}
*/
- const processDependency = dep => {
+ const processDependency = (dep) => {
const exportDesc = dep.getExports(moduleGraph);
if (!exportDesc) return;
exportsSpecsFromDependencies.set(dep, exportDesc);
@@ -399,7 +399,7 @@ class FlagDependencyExportsPlugin {
callback
);
},
- err => {
+ (err) => {
logger.timeEnd("store provided exports into cache");
callback(err);
}
@@ -411,13 +411,13 @@ class FlagDependencyExportsPlugin {
/** @type {WeakMap} */
const providedExportsCache = new WeakMap();
- compilation.hooks.rebuildModule.tap(PLUGIN_NAME, module => {
+ compilation.hooks.rebuildModule.tap(PLUGIN_NAME, (module) => {
providedExportsCache.set(
module,
moduleGraph.getExportsInfo(module).getRestoreProvidedData()
);
});
- compilation.hooks.finishRebuildingModule.tap(PLUGIN_NAME, module => {
+ compilation.hooks.finishRebuildingModule.tap(PLUGIN_NAME, (module) => {
moduleGraph.getExportsInfo(module).restoreProvided(
/** @type {RestoreProvidedData} */
(providedExportsCache.get(module))
diff --git a/lib/FlagDependencyUsagePlugin.js b/lib/FlagDependencyUsagePlugin.js
index bce1dbe403d..9f6e761f005 100644
--- a/lib/FlagDependencyUsagePlugin.js
+++ b/lib/FlagDependencyUsagePlugin.js
@@ -41,11 +41,11 @@ class FlagDependencyUsagePlugin {
* @returns {void}
*/
apply(compiler) {
- compiler.hooks.compilation.tap(PLUGIN_NAME, compilation => {
+ compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
const moduleGraph = compilation.moduleGraph;
compilation.hooks.optimizeDependencies.tap(
{ name: PLUGIN_NAME, stage: STAGE_DEFAULT },
- modules => {
+ (modules) => {
if (compilation.moduleMemCaches) {
throw new Error(
"optimization.usedExports can't be used with cacheUnaffected as export usage is a global effect"
@@ -108,7 +108,7 @@ class FlagDependencyUsagePlugin {
if (nestedInfo) {
if (
exportInfo.setUsedConditionally(
- used => used === UsageState.Unused,
+ (used) => used === UsageState.Unused,
UsageState.OnlyPropertiesUsed,
runtime
)
@@ -127,7 +127,7 @@ class FlagDependencyUsagePlugin {
}
if (
exportInfo.setUsedConditionally(
- v => v !== UsageState.Used,
+ (v) => v !== UsageState.Used,
UsageState.Used,
runtime
)
diff --git a/lib/FlagEntryExportAsUsedPlugin.js b/lib/FlagEntryExportAsUsedPlugin.js
index d2826d12fb2..71e770d92ae 100644
--- a/lib/FlagEntryExportAsUsedPlugin.js
+++ b/lib/FlagEntryExportAsUsedPlugin.js
@@ -27,7 +27,7 @@ class FlagEntryExportAsUsedPlugin {
* @returns {void}
*/
apply(compiler) {
- compiler.hooks.thisCompilation.tap(PLUGIN_NAME, compilation => {
+ compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {
const moduleGraph = compilation.moduleGraph;
compilation.hooks.seal.tap(PLUGIN_NAME, () => {
for (const [
diff --git a/lib/HotModuleReplacementPlugin.js b/lib/HotModuleReplacementPlugin.js
index 9e63892ad81..9d8fd2d46bb 100644
--- a/lib/HotModuleReplacementPlugin.js
+++ b/lib/HotModuleReplacementPlugin.js
@@ -123,7 +123,7 @@ class HotModuleReplacementPlugin {
const { hotAcceptCallback, hotAcceptWithoutCallback } =
HotModuleReplacementPlugin.getParserHooks(parser);
- return expr => {
+ return (expr) => {
const module = parser.state.module;
const dep = new ConstDependency(
`${module.moduleArgument}.hot.accept`,
@@ -145,7 +145,7 @@ class HotModuleReplacementPlugin {
} else if (arg.isArray()) {
params =
/** @type {BasicEvaluatedExpression[]} */
- (arg.items).filter(param => param.isString());
+ (arg.items).filter((param) => param.isString());
}
/** @type {string[]} */
const requests = [];
@@ -185,7 +185,7 @@ class HotModuleReplacementPlugin {
* @param {typeof ModuleHotDeclineDependency} ParamDependency dependency
* @returns {(expr: CallExpression) => boolean | undefined} callback
*/
- const createDeclineHandler = (parser, ParamDependency) => expr => {
+ const createDeclineHandler = (parser, ParamDependency) => (expr) => {
const module = parser.state.module;
const dep = new ConstDependency(
`${module.moduleArgument}.hot.decline`,
@@ -205,7 +205,7 @@ class HotModuleReplacementPlugin {
} else if (arg.isArray()) {
params =
/** @type {BasicEvaluatedExpression[]} */
- (arg.items).filter(param => param.isString());
+ (arg.items).filter((param) => param.isString());
}
for (const [idx, param] of params.entries()) {
const dep = new ParamDependency(
@@ -225,7 +225,7 @@ class HotModuleReplacementPlugin {
* @param {JavascriptParser} parser the parser
* @returns {(expr: Expression) => boolean | undefined} callback
*/
- const createHMRExpressionHandler = parser => expr => {
+ const createHMRExpressionHandler = (parser) => (expr) => {
const module = parser.state.module;
const dep = new ConstDependency(
`${module.moduleArgument}.hot`,
@@ -243,13 +243,13 @@ class HotModuleReplacementPlugin {
* @param {JavascriptParser} parser the parser
* @returns {void}
*/
- const applyModuleHot = parser => {
+ const applyModuleHot = (parser) => {
parser.hooks.evaluateIdentifier.for("module.hot").tap(
{
name: PLUGIN_NAME,
before: "NodeStuffPlugin"
},
- expr =>
+ (expr) =>
evaluateToIdentifier(
"module.hot",
"module",
@@ -278,10 +278,10 @@ class HotModuleReplacementPlugin {
* @param {JavascriptParser} parser the parser
* @returns {void}
*/
- const applyImportMetaHot = parser => {
+ const applyImportMetaHot = (parser) => {
parser.hooks.evaluateIdentifier
.for("import.meta.webpackHot")
- .tap(PLUGIN_NAME, expr =>
+ .tap(PLUGIN_NAME, (expr) =>
evaluateToIdentifier(
"import.meta.webpackHot",
"import.meta",
@@ -381,7 +381,7 @@ class HotModuleReplacementPlugin {
chunk,
compareModulesById(chunkGraph)
),
- m => /** @type {ModuleId} */ (chunkGraph.getModuleId(m))
+ (m) => /** @type {ModuleId} */ (chunkGraph.getModuleId(m))
);
}
});
@@ -391,7 +391,7 @@ class HotModuleReplacementPlugin {
const fullHashModules = new TupleSet();
/** @type {TupleSet} */
const nonCodeGeneratedModules = new TupleSet();
- compilation.hooks.fullHash.tap(PLUGIN_NAME, hash => {
+ compilation.hooks.fullHash.tap(PLUGIN_NAME, (hash) => {
const chunkGraph = compilation.chunkGraph;
const records = /** @type {Records} */ (compilation.records);
for (const chunk of compilation.chunks) {
@@ -399,7 +399,7 @@ class HotModuleReplacementPlugin {
* @param {Module} module module
* @returns {string} module hash
*/
- const getModuleHash = module => {
+ const getModuleHash = (module) => {
if (
compilation.codeGenerationResults.has(module, chunk.runtime)
) {
@@ -524,7 +524,7 @@ class HotModuleReplacementPlugin {
const runtime = keyToRuntime(chunkRuntime[key]);
allOldRuntime = mergeRuntimeOwned(allOldRuntime, runtime);
}
- forEachRuntime(allOldRuntime, runtime => {
+ forEachRuntime(allOldRuntime, (runtime) => {
const { path: filename, info: assetInfo } =
compilation.getPathWithInfo(
/** @type {NonNullable} */
@@ -588,7 +588,7 @@ class HotModuleReplacementPlugin {
let removedFromRuntime;
const currentChunk = find(
compilation.chunks,
- chunk => `${chunk.id}` === key
+ (chunk) => `${chunk.id}` === key
);
if (currentChunk) {
chunkId = currentChunk.id;
@@ -599,22 +599,22 @@ class HotModuleReplacementPlugin {
if (newRuntime === undefined) continue;
newModules = chunkGraph
.getChunkModules(currentChunk)
- .filter(module => updatedModules.has(module, currentChunk));
+ .filter((module) => updatedModules.has(module, currentChunk));
newRuntimeModules = [
...chunkGraph.getChunkRuntimeModulesIterable(currentChunk)
- ].filter(module => updatedModules.has(module, currentChunk));
+ ].filter((module) => updatedModules.has(module, currentChunk));
const fullHashModules =
chunkGraph.getChunkFullHashModulesIterable(currentChunk);
newFullHashModules =
fullHashModules &&
- [...fullHashModules].filter(module =>
+ [...fullHashModules].filter((module) =>
updatedModules.has(module, currentChunk)
);
const dependentHashModules =
chunkGraph.getChunkDependentHashModulesIterable(currentChunk);
newDependentHashModules =
dependentHashModules &&
- [...dependentHashModules].filter(module =>
+ [...dependentHashModules].filter((module) =>
updatedModules.has(module, currentChunk)
);
removedFromRuntime = subtractRuntime(oldRuntime, newRuntime);
@@ -626,7 +626,7 @@ class HotModuleReplacementPlugin {
}
if (removedFromRuntime) {
// chunk was removed from some runtimes
- forEachRuntime(removedFromRuntime, runtime => {
+ forEachRuntime(removedFromRuntime, (runtime) => {
const item =
/** @type {HotUpdateMainContentByRuntimeItem} */
(
@@ -665,7 +665,7 @@ class HotModuleReplacementPlugin {
// module is no longer in this runtime combination
// We (incorrectly) assume that it's not in an overlapping runtime combination
// and dispose it from the main runtimes the chunk was removed from
- forEachRuntime(removedFromRuntime, runtime => {
+ forEachRuntime(removedFromRuntime, (runtime) => {
// If the module is still used in this runtime, do not dispose it
// This could create a bad runtime state where the module is still loaded,
// but no chunk which contains it. This means we don't receive further HMR updates
@@ -764,7 +764,7 @@ class HotModuleReplacementPlugin {
compilation.hooks.chunkAsset.call(currentChunk, filename);
}
}
- forEachRuntime(newRuntime, runtime => {
+ forEachRuntime(newRuntime, (runtime) => {
const item =
/** @type {HotUpdateMainContentByRuntimeItem} */ (
hotUpdateMainContentByRuntime.get(
@@ -829,7 +829,7 @@ To fix this, make sure to include [runtime] in the output.hotUpdateMainFilename
...completelyRemovedModulesArray,
...Array.from(
removedModules,
- m =>
+ (m) =>
/** @type {ModuleId} */ (chunkGraph.getModuleId(m))
)
]
@@ -863,28 +863,28 @@ To fix this, make sure to include [runtime] in the output.hotUpdateMainFilename
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_AUTO)
- .tap(PLUGIN_NAME, parser => {
+ .tap(PLUGIN_NAME, (parser) => {
applyModuleHot(parser);
applyImportMetaHot(parser);
});
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_DYNAMIC)
- .tap(PLUGIN_NAME, parser => {
+ .tap(PLUGIN_NAME, (parser) => {
applyModuleHot(parser);
});
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_ESM)
- .tap(PLUGIN_NAME, parser => {
+ .tap(PLUGIN_NAME, (parser) => {
applyImportMetaHot(parser);
});
- normalModuleFactory.hooks.module.tap(PLUGIN_NAME, module => {
+ normalModuleFactory.hooks.module.tap(PLUGIN_NAME, (module) => {
module.hot = true;
return module;
});
NormalModule.getCompilationHooks(compilation).loader.tap(
PLUGIN_NAME,
- context => {
+ (context) => {
context.hot = true;
}
);
diff --git a/lib/IgnorePlugin.js b/lib/IgnorePlugin.js
index 004aa8d8c9e..310af5ee2f1 100644
--- a/lib/IgnorePlugin.js
+++ b/lib/IgnorePlugin.js
@@ -71,8 +71,8 @@ class IgnorePlugin {
* @returns {void}
*/
apply(compiler) {
- compiler.hooks.normalModuleFactory.tap(PLUGIN_NAME, nmf => {
- nmf.hooks.beforeResolve.tap(PLUGIN_NAME, resolveData => {
+ compiler.hooks.normalModuleFactory.tap(PLUGIN_NAME, (nmf) => {
+ nmf.hooks.beforeResolve.tap(PLUGIN_NAME, (resolveData) => {
const result = this.checkIgnore(resolveData);
if (
@@ -93,7 +93,7 @@ class IgnorePlugin {
return result;
});
});
- compiler.hooks.contextModuleFactory.tap(PLUGIN_NAME, cmf => {
+ compiler.hooks.contextModuleFactory.tap(PLUGIN_NAME, (cmf) => {
cmf.hooks.beforeResolve.tap(PLUGIN_NAME, this.checkIgnore);
});
}
diff --git a/lib/IgnoreWarningsPlugin.js b/lib/IgnoreWarningsPlugin.js
index 5518b648dd7..de5fd35e23b 100644
--- a/lib/IgnoreWarningsPlugin.js
+++ b/lib/IgnoreWarningsPlugin.js
@@ -24,11 +24,11 @@ class IgnoreWarningsPlugin {
* @returns {void}
*/
apply(compiler) {
- compiler.hooks.compilation.tap(PLUGIN_NAME, compilation => {
- compilation.hooks.processWarnings.tap(PLUGIN_NAME, warnings =>
+ compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
+ compilation.hooks.processWarnings.tap(PLUGIN_NAME, (warnings) =>
warnings.filter(
- warning =>
- !this._ignoreWarnings.some(ignore => ignore(warning, compilation))
+ (warning) =>
+ !this._ignoreWarnings.some((ignore) => ignore(warning, compilation))
)
);
});
diff --git a/lib/InitFragment.js b/lib/InitFragment.js
index 228f592a4ff..e06f8e906b6 100644
--- a/lib/InitFragment.js
+++ b/lib/InitFragment.js
@@ -173,6 +173,12 @@ makeSerializable(InitFragment, "webpack/lib/InitFragment");
InitFragment.prototype.merge =
/** @type {TODO} */
(undefined);
+InitFragment.prototype.getImported =
+ /** @type {TODO} */
+ (undefined);
+InitFragment.prototype.setImported =
+ /** @type {TODO} */
+ (undefined);
InitFragment.STAGE_CONSTANTS = 10;
InitFragment.STAGE_ASYNC_BOUNDARY = 20;
diff --git a/lib/InvalidDependenciesModuleWarning.js b/lib/InvalidDependenciesModuleWarning.js
index b77d991b379..7fb7d3c6c4a 100644
--- a/lib/InvalidDependenciesModuleWarning.js
+++ b/lib/InvalidDependenciesModuleWarning.js
@@ -18,7 +18,7 @@ class InvalidDependenciesModuleWarning extends WebpackError {
*/
constructor(module, deps) {
const orderedDeps = deps ? [...deps].sort() : [];
- const depsList = orderedDeps.map(dep => ` * ${JSON.stringify(dep)}`);
+ const depsList = orderedDeps.map((dep) => ` * ${JSON.stringify(dep)}`);
super(`Invalid dependencies have been reported by plugins or loaders for this module. All reported dependencies need to be absolute paths.
Invalid dependencies may lead to broken watching and caching.
As best effort we try to convert all invalid values to absolute paths and converting globs into context dependencies, but this is deprecated behavior.
diff --git a/lib/JavascriptMetaInfoPlugin.js b/lib/JavascriptMetaInfoPlugin.js
index 35fcb68c14a..e3d9ffa8b90 100644
--- a/lib/JavascriptMetaInfoPlugin.js
+++ b/lib/JavascriptMetaInfoPlugin.js
@@ -32,7 +32,7 @@ class JavascriptMetaInfoPlugin {
* @param {JavascriptParser} parser the parser
* @returns {void}
*/
- const handler = parser => {
+ const handler = (parser) => {
parser.hooks.call.for("eval").tap(PLUGIN_NAME, () => {
const buildInfo =
/** @type {BuildInfo} */
diff --git a/lib/LibManifestPlugin.js b/lib/LibManifestPlugin.js
index b364564dd34..4d6a1e8e1ef 100644
--- a/lib/LibManifestPlugin.js
+++ b/lib/LibManifestPlugin.js
@@ -86,7 +86,7 @@ class LibManifestPlugin {
this.options.entryOnly &&
!someInIterable(
moduleGraph.getIncomingConnections(module),
- c => c.dependency instanceof EntryDependency
+ (c) => c.dependency instanceof EntryDependency
)
) {
continue;
@@ -129,7 +129,7 @@ class LibManifestPlugin {
mkdirp(
intermediateFileSystem,
dirname(intermediateFileSystem, targetPath),
- err => {
+ (err) => {
if (err) return callback(err);
intermediateFileSystem.writeFile(targetPath, buffer, callback);
}
diff --git a/lib/LoaderOptionsPlugin.js b/lib/LoaderOptionsPlugin.js
index 2d5ae88479a..4c803f92e9f 100644
--- a/lib/LoaderOptionsPlugin.js
+++ b/lib/LoaderOptionsPlugin.js
@@ -59,7 +59,7 @@ class LoaderOptionsPlugin {
*/
apply(compiler) {
const options = this.options;
- compiler.hooks.compilation.tap(PLUGIN_NAME, compilation => {
+ compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
NormalModule.getCompilationHooks(compilation).loader.tap(
PLUGIN_NAME,
(context, module) => {
diff --git a/lib/LoaderTargetPlugin.js b/lib/LoaderTargetPlugin.js
index e6ea9810db6..8f3664122c3 100644
--- a/lib/LoaderTargetPlugin.js
+++ b/lib/LoaderTargetPlugin.js
@@ -25,10 +25,10 @@ class LoaderTargetPlugin {
* @returns {void}
*/
apply(compiler) {
- compiler.hooks.compilation.tap(PLUGIN_NAME, compilation => {
+ compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
NormalModule.getCompilationHooks(compilation).loader.tap(
PLUGIN_NAME,
- loaderContext => {
+ (loaderContext) => {
loaderContext.target = this.target;
}
);
diff --git a/lib/MainTemplate.js b/lib/MainTemplate.js
index 599f4fe1c16..a793b1a8319 100644
--- a/lib/MainTemplate.js
+++ b/lib/MainTemplate.js
@@ -323,7 +323,7 @@ class MainTemplate {
/**
* @param {PathData} options context data
* @returns {string} interpolated path
- */ options =>
+ */ (options) =>
compilation.getAssetPath(
/** @type {string} */
(compilation.outputOptions.publicPath),
diff --git a/lib/Module.js b/lib/Module.js
index 9e325a2507e..899b26a84b4 100644
--- a/lib/Module.js
+++ b/lib/Module.js
@@ -775,7 +775,7 @@ class Module extends DependenciesBlock {
fromModule,
connections
] of moduleGraph.getIncomingConnectionsByOriginModule(this)) {
- if (!connections.some(c => c.isTargetActive(chunk.runtime))) continue;
+ if (!connections.some((c) => c.isTargetActive(chunk.runtime))) continue;
for (const originChunk of chunkGraph.getModuleChunksIterable(
/** @type {Module} */ (fromModule)
)) {
diff --git a/lib/ModuleFilenameHelpers.js b/lib/ModuleFilenameHelpers.js
index 0abb1220e9a..0ef302e1337 100644
--- a/lib/ModuleFilenameHelpers.js
+++ b/lib/ModuleFilenameHelpers.js
@@ -96,13 +96,13 @@ const getHash =
* @param {Record T>} obj the object to convert to a lazy access object
* @returns {T} the lazy access object
*/
-const lazyObject = obj => {
+const lazyObject = (obj) => {
const newObj = /** @type {T} */ ({});
for (const key of Object.keys(obj)) {
const fn = obj[key];
Object.defineProperty(newObj, key, {
get: () => fn(),
- set: v => {
+ set: (v) => {
Object.defineProperty(newObj, key, {
value: v,
enumerable: true,
@@ -320,7 +320,7 @@ ModuleFilenameHelpers.replaceDuplicates = (array, fn, comparator) => {
const matchPart = (str, test) => {
if (!test) return true;
if (Array.isArray(test)) {
- return test.some(test => matchPart(str, test));
+ return test.some((test) => matchPart(str, test));
}
if (typeof test === "string") {
return str.startsWith(test);
diff --git a/lib/ModuleGraph.js b/lib/ModuleGraph.js
index 554bbde0493..20bf162c142 100644
--- a/lib/ModuleGraph.js
+++ b/lib/ModuleGraph.js
@@ -11,6 +11,7 @@ const ModuleGraphConnection = require("./ModuleGraphConnection");
const SortableSet = require("./util/SortableSet");
const WeakTupleMap = require("./util/WeakTupleMap");
const { sortWithSourceOrder } = require("./util/comparators");
+const memoize = require("./util/memoize");
/** @typedef {import("./Compilation").ModuleMemCaches} ModuleMemCaches */
/** @typedef {import("./DependenciesBlock")} DependenciesBlock */
@@ -24,6 +25,10 @@ const { sortWithSourceOrder } = require("./util/comparators");
/** @typedef {import("./dependencies/HarmonyImportSpecifierDependency")} HarmonyImportSpecifierDependency */
/** @typedef {import("./util/comparators").DependencySourceOrder} DependencySourceOrder */
+const getCommonJsSelfReferenceDependency = memoize(() =>
+ require("./dependencies/CommonJsSelfReferenceDependency")
+);
+
/**
* @callback OptimizationBailoutFunction
* @param {RequestShortener} requestShortener
@@ -36,7 +41,7 @@ const EMPTY_SET = new Set();
* @param {SortableSet} set input
* @returns {readonly Map} mapped by origin module
*/
-const getConnectionsByOriginModule = set => {
+const getConnectionsByOriginModule = (set) => {
const map = new Map();
/** @type {Module | 0} */
let lastModule = 0;
@@ -67,7 +72,7 @@ const getConnectionsByOriginModule = set => {
* @param {SortableSet} set input
* @returns {readonly Map} mapped by module
*/
-const getConnectionsByModule = set => {
+const getConnectionsByModule = (set) => {
const map = new Map();
/** @type {Module | 0} */
let lastModule = 0;
@@ -840,8 +845,7 @@ class ModuleGraph {
for (const connection of connections) {
if (
!connection.dependency ||
- connection.dependency instanceof
- require("./dependencies/CommonJsSelfReferenceDependency")
+ connection.dependency instanceof getCommonJsSelfReferenceDependency()
) {
continue;
}
@@ -956,7 +960,7 @@ class ModuleGraph {
* @param {Module} module the module
* @returns {ModuleGraph} the module graph
*/
- module => {
+ (module) => {
const moduleGraph = moduleGraphForModuleMap.get(module);
if (!moduleGraph) {
throw new Error(
diff --git a/lib/ModuleInfoHeaderPlugin.js b/lib/ModuleInfoHeaderPlugin.js
index 58ad847d3f1..5aecdb2ca62 100644
--- a/lib/ModuleInfoHeaderPlugin.js
+++ b/lib/ModuleInfoHeaderPlugin.js
@@ -26,7 +26,7 @@ const JavascriptModulesPlugin = require("./javascript/JavascriptModulesPlugin");
* @param {Iterable} iterable iterable
* @returns {string} joined with comma
*/
-const joinIterableWithComma = iterable => {
+const joinIterableWithComma = (iterable) => {
// This is more performant than Array.from().join(", ")
// as it doesn't create an array
let str = "";
@@ -94,7 +94,7 @@ const printExportsInfoToSource = (
? ` -> ${target.module.readableIdentifier(requestShortener)}${
target.export
? ` .${target.export
- .map(e => JSON.stringify(e).slice(1, -1))
+ .map((e) => JSON.stringify(e).slice(1, -1))
.join(".")}`
: ""
}`
@@ -165,7 +165,7 @@ class ModuleInfoHeaderPlugin {
*/
apply(compiler) {
const { _verbose: verbose } = this;
- compiler.hooks.compilation.tap(PLUGIN_NAME, compilation => {
+ compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
const javascriptHooks =
JavascriptModulesPlugin.getCompilationHooks(compilation);
javascriptHooks.renderModulePackage.tap(
diff --git a/lib/ModuleParseError.js b/lib/ModuleParseError.js
index dae44e05839..54774bb579a 100644
--- a/lib/ModuleParseError.js
+++ b/lib/ModuleParseError.js
@@ -43,7 +43,7 @@ class ModuleParseError extends WebpackError {
"\nYou may need an appropriate loader to handle this file type.";
} else if (loaders.length >= 1) {
message += `\nFile was processed with these loaders:${loaders
- .map(loader => `\n * ${loader}`)
+ .map((loader) => `\n * ${loader}`)
.join("")}`;
message +=
"\nYou may need an additional loader to handle the result of these loaders.";
@@ -75,8 +75,10 @@ class ModuleParseError extends WebpackError {
const linesAfter = sourceLines.slice(lineNumber, lineNumber + 2);
message += `${linesBefore
- .map(l => `\n| ${l}`)
- .join("")}\n> ${theLine}${linesAfter.map(l => `\n| ${l}`).join("")}`;
+ .map((l) => `\n| ${l}`)
+ .join(
+ ""
+ )}\n> ${theLine}${linesAfter.map((l) => `\n| ${l}`).join("")}`;
}
loc = { start: err.loc };
diff --git a/lib/MultiCompiler.js b/lib/MultiCompiler.js
index 6e0c4e9f0e0..3ab64e4affc 100644
--- a/lib/MultiCompiler.js
+++ b/lib/MultiCompiler.js
@@ -16,6 +16,7 @@ const ArrayQueue = require("./util/ArrayQueue");
/** @template T @typedef {import("tapable").AsyncSeriesHook} AsyncSeriesHook */
/** @template T @template R @typedef {import("tapable").SyncBailHook} SyncBailHook */
+/** @typedef {import("../declarations/WebpackOptions").WebpackOptions} WebpackOptions */
/** @typedef {import("../declarations/WebpackOptions").WatchOptions} WatchOptions */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./Stats")} Stats */
@@ -44,6 +45,8 @@ const ArrayQueue = require("./util/ArrayQueue");
* @property {number=} parallelism how many Compilers are allows to run at the same time in parallel
*/
+/** @typedef {ReadonlyArray & MultiCompilerOptions} MultiWebpackOptions */
+
const CLASS_NAME = "MultiCompiler";
module.exports = class MultiCompiler {
@@ -54,7 +57,7 @@ module.exports = class MultiCompiler {
constructor(compilers, options) {
if (!Array.isArray(compilers)) {
/** @type {Compiler[]} */
- compilers = Object.keys(compilers).map(name => {
+ compilers = Object.keys(compilers).map((name) => {
/** @type {Record} */
(compilers)[name].name = name;
return /** @type {Record} */ (compilers)[name];
@@ -65,16 +68,16 @@ module.exports = class MultiCompiler {
/** @type {SyncHook<[MultiStats]>} */
done: new SyncHook(["stats"]),
/** @type {MultiHook>} */
- invalid: new MultiHook(compilers.map(c => c.hooks.invalid)),
+ invalid: new MultiHook(compilers.map((c) => c.hooks.invalid)),
/** @type {MultiHook>} */
- run: new MultiHook(compilers.map(c => c.hooks.run)),
+ run: new MultiHook(compilers.map((c) => c.hooks.run)),
/** @type {SyncHook<[]>} */
watchClose: new SyncHook([]),
/** @type {MultiHook>} */
- watchRun: new MultiHook(compilers.map(c => c.hooks.watchRun)),
+ watchRun: new MultiHook(compilers.map((c) => c.hooks.watchRun)),
/** @type {MultiHook>} */
infrastructureLog: new MultiHook(
- compilers.map(c => c.hooks.infrastructureLog)
+ compilers.map((c) => c.hooks.infrastructureLog)
)
});
this.compilers = compilers;
@@ -94,7 +97,7 @@ module.exports = class MultiCompiler {
const compilerIndex = index;
let compilerDone = false;
// eslint-disable-next-line no-loop-func
- compiler.hooks.done.tap(CLASS_NAME, stats => {
+ compiler.hooks.done.tap(CLASS_NAME, (stats) => {
if (!compilerDone) {
compilerDone = true;
doneCompilers++;
@@ -124,7 +127,7 @@ module.exports = class MultiCompiler {
* @param {WebpackError} warning warning
*/
const addWarning = (compiler, warning) => {
- compiler.hooks.thisCompilation.tap(CLASS_NAME, compilation => {
+ compiler.hooks.thisCompilation.tap(CLASS_NAME, (compilation) => {
compilation.warnings.push(warning);
});
};
@@ -152,7 +155,7 @@ module.exports = class MultiCompiler {
get options() {
return Object.assign(
- this.compilers.map(c => c.options),
+ this.compilers.map((c) => c.options),
this._options
);
}
@@ -254,7 +257,7 @@ module.exports = class MultiCompiler {
* @param {Compiler} compiler compiler
* @returns {boolean} target was found
*/
- const targetFound = compiler => {
+ const targetFound = (compiler) => {
for (const edge of edges) {
if (edge.target === compiler) {
return true;
@@ -276,7 +279,7 @@ module.exports = class MultiCompiler {
const dependencies = this.dependencies.get(source);
if (dependencies) {
for (const dep of dependencies) {
- const target = this.compilers.find(c => c.name === dep);
+ const target = this.compilers.find((c) => c.name === dep);
if (!target) {
missing.push(dep);
} else {
@@ -289,8 +292,10 @@ module.exports = class MultiCompiler {
}
}
/** @type {string[]} */
- const errors = missing.map(m => `Compiler dependency \`${m}\` not found.`);
- const stack = this.compilers.filter(c => !targetFound(c));
+ const errors = missing.map(
+ (m) => `Compiler dependency \`${m}\` not found.`
+ );
+ const stack = this.compilers.filter((c) => !targetFound(c));
while (stack.length > 0) {
const current = stack.pop();
for (const edge of edges) {
@@ -307,7 +312,7 @@ module.exports = class MultiCompiler {
/** @type {string[]} */
const lines = [...edges]
.sort(sortEdges)
- .map(edge => `${edge.source.name} -> ${edge.target.name}`);
+ .map((edge) => `${edge.source.name} -> ${edge.target.name}`);
lines.unshift("Circular dependency found in compiler dependencies.");
errors.unshift(lines.join("\n"));
}
@@ -334,7 +339,7 @@ module.exports = class MultiCompiler {
* @param {string} d dependency
* @returns {boolean} when dependency was fulfilled
*/
- const isDependencyFulfilled = d => fulfilledNames.has(d);
+ const isDependencyFulfilled = (d) => fulfilledNames.has(d);
/**
* @returns {Compiler[]} compilers
*/
@@ -358,12 +363,12 @@ module.exports = class MultiCompiler {
* @param {Callback} callback callback
* @returns {void}
*/
- const runCompilers = callback => {
+ const runCompilers = (callback) => {
if (remainingCompilers.length === 0) return callback(null);
asyncLib.map(
getReadyCompilers(),
(compiler, callback) => {
- fn(compiler, err => {
+ fn(compiler, (err) => {
if (err) return callback(err);
fulfilledNames.add(compiler.name);
runCompilers(callback);
@@ -400,7 +405,7 @@ module.exports = class MultiCompiler {
// running-outdated -> blocked [running--] (when compilation is done)
/** @type {Node[]} */
- const nodes = this.compilers.map(compiler => ({
+ const nodes = this.compilers.map((compiler) => ({
compiler,
setupResult: undefined,
result: undefined,
@@ -472,7 +477,7 @@ module.exports = class MultiCompiler {
* @param {Node} node node
* @returns {void}
*/
- const nodeInvalidFromParent = node => {
+ const nodeInvalidFromParent = (node) => {
if (node.state === "done") {
node.state = "blocked";
} else if (node.state === "running") {
@@ -486,7 +491,7 @@ module.exports = class MultiCompiler {
* @param {Node} node node
* @returns {void}
*/
- const nodeInvalid = node => {
+ const nodeInvalid = (node) => {
if (node.state === "done") {
node.state = "pending";
} else if (node.state === "running") {
@@ -500,7 +505,7 @@ module.exports = class MultiCompiler {
* @param {Node} node node
* @returns {void}
*/
- const nodeChange = node => {
+ const nodeChange = (node) => {
nodeInvalid(node);
if (node.state === "pending") {
node.state = "blocked";
@@ -538,7 +543,7 @@ module.exports = class MultiCompiler {
if (
node.state === "queued" ||
(node.state === "blocked" &&
- node.parents.every(p => p.state === "done"))
+ node.parents.every((p) => p.state === "done"))
) {
running++;
node.state = "starting";
@@ -554,7 +559,7 @@ module.exports = class MultiCompiler {
if (
!errored &&
running === 0 &&
- nodes.every(node => node.state === "done")
+ nodes.every((node) => node.state === "done")
) {
const stats = [];
for (const node of nodes) {
@@ -574,7 +579,7 @@ module.exports = class MultiCompiler {
}
/**
- * @param {WatchOptions|WatchOptions[]} watchOptions the watcher's options
+ * @param {WatchOptions | WatchOptions[]} watchOptions the watcher's options
* @param {Callback} handler signals when the call finishes
* @returns {MultiWatching} a compiler watcher
*/
@@ -653,7 +658,7 @@ module.exports = class MultiCompiler {
(compiler, callback) => {
compiler.close(callback);
},
- error => {
+ (error) => {
callback(error);
}
);
diff --git a/lib/MultiStats.js b/lib/MultiStats.js
index 73ab807942f..62504ab8234 100644
--- a/lib/MultiStats.js
+++ b/lib/MultiStats.js
@@ -25,6 +25,8 @@ const indent = (str, prefix) => {
return prefix + rem;
};
+/** @typedef {undefined | string | boolean | StatsOptions} ChildrenStatsOptions */
+/** @typedef {Omit & { children?: ChildrenStatsOptions | ChildrenStatsOptions[] }} MultiStatsOptions */
/** @typedef {{ version: boolean, hash: boolean, errorsCount: boolean, warningsCount: boolean, errors: boolean, warnings: boolean, children: NormalizedStatsOptions[] }} ChildOptions */
class MultiStats {
@@ -36,25 +38,25 @@ class MultiStats {
}
get hash() {
- return this.stats.map(stat => stat.hash).join("");
+ return this.stats.map((stat) => stat.hash).join("");
}
/**
* @returns {boolean} true if a child compilation encountered an error
*/
hasErrors() {
- return this.stats.some(stat => stat.hasErrors());
+ return this.stats.some((stat) => stat.hasErrors());
}
/**
* @returns {boolean} true if a child compilation had a warning
*/
hasWarnings() {
- return this.stats.some(stat => stat.hasWarnings());
+ return this.stats.some((stat) => stat.hasWarnings());
}
/**
- * @param {string | boolean | StatsOptions | undefined} options stats options
+ * @param {undefined | string | boolean | MultiStatsOptions} options stats options
* @param {CreateStatsOptionsContext} context context
* @returns {ChildOptions} context context
*/
@@ -80,6 +82,9 @@ class MultiStats {
const childOptions = Array.isArray(childrenOptions)
? childrenOptions[idx]
: childrenOptions;
+ if (typeof childOptions === "boolean") {
+ return stat.compilation.createStatsOptions(childOptions, context);
+ }
return stat.compilation.createStatsOptions(
{
...baseOptions,
@@ -93,18 +98,18 @@ class MultiStats {
);
});
return {
- version: children.every(o => o.version),
- hash: children.every(o => o.hash),
- errorsCount: children.every(o => o.errorsCount),
- warningsCount: children.every(o => o.warningsCount),
- errors: children.every(o => o.errors),
- warnings: children.every(o => o.warnings),
+ version: children.every((o) => o.version),
+ hash: children.every((o) => o.hash),
+ errorsCount: children.every((o) => o.errorsCount),
+ warningsCount: children.every((o) => o.warningsCount),
+ errors: children.every((o) => o.errors),
+ warnings: children.every((o) => o.warnings),
children
};
}
/**
- * @param {(string | boolean | StatsOptions)=} options stats options
+ * @param {(string | boolean | MultiStatsOptions)=} options stats options
* @returns {StatsCompilation} json output
*/
toJson(options) {
@@ -130,7 +135,7 @@ class MultiStats {
obj.version = obj.children[0].version;
}
if (childOptions.hash) {
- obj.hash = obj.children.map(j => j.hash).join("");
+ obj.hash = obj.children.map((j) => j.hash).join("");
}
/**
* @param {StatsCompilation} j stats error
@@ -179,7 +184,7 @@ class MultiStats {
}
/**
- * @param {(string | boolean | StatsOptions)=} options stats options
+ * @param {(string | boolean | MultiStatsOptions)=} options stats options
* @returns {string} string output
*/
toString(options) {
diff --git a/lib/MultiWatching.js b/lib/MultiWatching.js
index cfe95f17b28..448ac96206a 100644
--- a/lib/MultiWatching.js
+++ b/lib/MultiWatching.js
@@ -67,7 +67,7 @@ class MultiWatching {
(watching, finishedCallback) => {
watching.close(finishedCallback);
},
- err => {
+ (err) => {
this.compiler.hooks.watchClose.call();
if (typeof callback === "function") {
this.compiler.running = false;
diff --git a/lib/NoEmitOnErrorsPlugin.js b/lib/NoEmitOnErrorsPlugin.js
index dfcde930954..f0a7f00332f 100644
--- a/lib/NoEmitOnErrorsPlugin.js
+++ b/lib/NoEmitOnErrorsPlugin.js
@@ -16,10 +16,10 @@ class NoEmitOnErrorsPlugin {
* @returns {void}
*/
apply(compiler) {
- compiler.hooks.shouldEmit.tap(PLUGIN_NAME, compilation => {
+ compiler.hooks.shouldEmit.tap(PLUGIN_NAME, (compilation) => {
if (compilation.getStats().hasErrors()) return false;
});
- compiler.hooks.compilation.tap(PLUGIN_NAME, compilation => {
+ compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
compilation.hooks.shouldRecord.tap(PLUGIN_NAME, () => {
if (compilation.getStats().hasErrors()) return false;
});
diff --git a/lib/NodeStuffPlugin.js b/lib/NodeStuffPlugin.js
index 87a5cd61405..6cd44b8d53f 100644
--- a/lib/NodeStuffPlugin.js
+++ b/lib/NodeStuffPlugin.js
@@ -74,7 +74,7 @@ class NodeStuffPlugin {
if (localOptions.global !== false) {
const withWarning = localOptions.global === "warn";
- parser.hooks.expression.for("global").tap(PLUGIN_NAME, expr => {
+ parser.hooks.expression.for("global").tap(PLUGIN_NAME, (expr) => {
const dep = new ConstDependency(
RuntimeGlobals.global,
/** @type {Range} */ (expr.range),
@@ -94,7 +94,7 @@ class NodeStuffPlugin {
);
}
});
- parser.hooks.rename.for("global").tap(PLUGIN_NAME, expr => {
+ parser.hooks.rename.for("global").tap(PLUGIN_NAME, (expr) => {
const dep = new ConstDependency(
RuntimeGlobals.global,
/** @type {Range} */ (expr.range),
@@ -115,10 +115,11 @@ class NodeStuffPlugin {
const setModuleConstant = (expressionName, fn, warning) => {
parser.hooks.expression
.for(expressionName)
- .tap(PLUGIN_NAME, expr => {
+ .tap(PLUGIN_NAME, (expr) => {
const dep = new CachedConstDependency(
JSON.stringify(fn(parser.state.module)),
- /** @type {Range} */ (expr.range),
+ /** @type {Range} */
+ (expr.range),
expressionName
);
dep.loc = /** @type {DependencyLocation} */ (expr.loc);
@@ -143,7 +144,7 @@ class NodeStuffPlugin {
const setUrlModuleConstant = (expressionName, fn) => {
parser.hooks.expression
.for(expressionName)
- .tap(PLUGIN_NAME, expr => {
+ .tap(PLUGIN_NAME, (expr) => {
const dep = new ExternalModuleDependency(
"url",
[
@@ -186,14 +187,19 @@ class NodeStuffPlugin {
"__filename is a Node.js feature and isn't available in browsers."
);
break;
- case "node-module":
+ case "node-module": {
+ const importMetaName =
+ /** @type {string} */
+ (compilation.outputOptions.importMetaName);
+
setUrlModuleConstant(
"__filename",
- functionName => `${functionName}(import.meta.url)`
+ (functionName) => `${functionName}(${importMetaName}.url)`
);
break;
+ }
case true:
- setModuleConstant("__filename", module =>
+ setModuleConstant("__filename", (module) =>
relative(
/** @type {InputFileSystem} */ (compiler.inputFileSystem),
context,
@@ -205,7 +211,7 @@ class NodeStuffPlugin {
parser.hooks.evaluateIdentifier
.for("__filename")
- .tap(PLUGIN_NAME, expr => {
+ .tap(PLUGIN_NAME, (expr) => {
if (!parser.state.module) return;
const resource = parseResource(parser.state.module.resource);
return evaluateToString(resource.path)(expr);
@@ -223,15 +229,20 @@ class NodeStuffPlugin {
"__dirname is a Node.js feature and isn't available in browsers."
);
break;
- case "node-module":
+ case "node-module": {
+ const importMetaName =
+ /** @type {string} */
+ (compilation.outputOptions.importMetaName);
+
setUrlModuleConstant(
"__dirname",
- functionName =>
- `${functionName}(import.meta.url + "/..").slice(0, -1)`
+ (functionName) =>
+ `${functionName}(${importMetaName}.url + "/..").slice(0, -1)`
);
break;
+ }
case true:
- setModuleConstant("__dirname", module =>
+ setModuleConstant("__dirname", (module) =>
relative(
/** @type {InputFileSystem} */ (compiler.inputFileSystem),
context,
@@ -243,10 +254,11 @@ class NodeStuffPlugin {
parser.hooks.evaluateIdentifier
.for("__dirname")
- .tap(PLUGIN_NAME, expr => {
+ .tap(PLUGIN_NAME, (expr) => {
if (!parser.state.module) return;
return evaluateToString(
- /** @type {string} */ (parser.state.module.context)
+ /** @type {string} */
+ (parser.state.module.context)
)(expr);
});
}
diff --git a/lib/NormalModule.js b/lib/NormalModule.js
index 20ff21b3b74..f9d4c2d95de 100644
--- a/lib/NormalModule.js
+++ b/lib/NormalModule.js
@@ -163,17 +163,17 @@ const contextifySourceMap = (context, sourceMap, associatedObjectForCache) => {
const { sourceRoot } = sourceMap;
/** @type {(source: string) => string} */
const mapper = !sourceRoot
- ? source => source
+ ? (source) => source
: sourceRoot.endsWith("/")
- ? source =>
+ ? (source) =>
source.startsWith("/")
? `${sourceRoot.slice(0, -1)}${source}`
: `${sourceRoot}${source}`
- : source =>
+ : (source) =>
source.startsWith("/")
? `${sourceRoot}${source}`
: `${sourceRoot}/${source}`;
- const newSources = sourceMap.sources.map(source =>
+ const newSources = sourceMap.sources.map((source) =>
contextifySourceUrl(context, mapper(source), associatedObjectForCache)
);
return {
@@ -188,7 +188,7 @@ const contextifySourceMap = (context, sourceMap, associatedObjectForCache) => {
* @param {string | Buffer} input the input
* @returns {string} the converted string
*/
-const asString = input => {
+const asString = (input) => {
if (Buffer.isBuffer(input)) {
return input.toString("utf8");
}
@@ -199,7 +199,7 @@ const asString = input => {
* @param {string | Buffer} input the input
* @returns {Buffer} the converted buffer
*/
-const asBuffer = input => {
+const asBuffer = (input) => {
if (!Buffer.isBuffer(input)) {
return Buffer.from(input, "utf8");
}
@@ -279,14 +279,14 @@ class NormalModule extends Module {
beforeParse: new SyncHook(["module"]),
beforeSnapshot: new SyncHook(["module"]),
// TODO webpack 6 deprecate
- readResourceForScheme: new HookMap(scheme => {
+ readResourceForScheme: new HookMap((scheme) => {
const hook =
/** @type {NormalModuleCompilationHooks} */
(hooks).readResource.for(scheme);
return createFakeHook(
/** @type {AsyncSeriesBailHook<[string, NormalModule], string | Buffer | null>} */ ({
tap: (options, fn) =>
- hook.tap(options, loaderContext =>
+ hook.tap(options, (loaderContext) =>
fn(
loaderContext.resource,
/** @type {NormalModule} */ (loaderContext._module)
@@ -301,7 +301,7 @@ class NormalModule extends Module {
)
),
tapPromise: (options, fn) =>
- hook.tapPromise(options, loaderContext =>
+ hook.tapPromise(options, (loaderContext) =>
fn(
loaderContext.resource,
/** @type {NormalModule} */ (loaderContext._module)
@@ -599,19 +599,19 @@ class NormalModule extends Module {
*/
const getResolveContext = () => ({
fileDependencies: {
- add: d =>
+ add: (d) =>
/** @type {LoaderContext} */ (
loaderContext
).addDependency(d)
},
contextDependencies: {
- add: d =>
+ add: (d) =>
/** @type {LoaderContext} */ (
loaderContext
).addContextDependency(d)
},
missingDependencies: {
- add: d =>
+ add: (d) =>
/** @type {LoaderContext} */ (
loaderContext
).addMissingDependency(d)
@@ -660,7 +660,7 @@ class NormalModule extends Module {
* @param {HashFunction=} type type
* @returns {Hash} hash
*/
- createHash: type =>
+ createHash: (type) =>
createHash(
type ||
/** @type {HashFunction} */
@@ -674,7 +674,7 @@ class NormalModule extends Module {
* @param {import("../declarations/LoaderContext").Schema=} schema schema
* @returns {T} options
*/
- getOptions: schema => {
+ getOptions: (schema) => {
const loader = this.getCurrentLoader(
/** @type {LoaderContext} */ (loaderContext)
);
@@ -716,7 +716,7 @@ class NormalModule extends Module {
return /** @type {T} */ (options);
},
- emitWarning: warning => {
+ emitWarning: (warning) => {
if (!(warning instanceof Error)) {
warning = new NonErrorEmittedError(warning);
}
@@ -726,7 +726,7 @@ class NormalModule extends Module {
})
);
},
- emitError: error => {
+ emitError: (error) => {
if (!(error instanceof Error)) {
error = new NonErrorEmittedError(error);
}
@@ -736,7 +736,7 @@ class NormalModule extends Module {
})
);
},
- getLogger: name => {
+ getLogger: (name) => {
const currentLoader = this.getCurrentLoader(
/** @type {LoaderContext} */ (loaderContext)
);
@@ -802,7 +802,7 @@ class NormalModule extends Module {
);
assetsInfo.set(name, assetInfo);
},
- addBuildDependency: dep => {
+ addBuildDependency: (dep) => {
const buildInfo = /** @type {BuildInfo} */ (this.buildInfo);
if (buildInfo.buildDependencies === undefined) {
@@ -1190,7 +1190,7 @@ class NormalModule extends Module {
const hooks = NormalModule.getCompilationHooks(compilation);
- return this._doBuild(options, compilation, resolver, fs, hooks, err => {
+ return this._doBuild(options, compilation, resolver, fs, hooks, (err) => {
// if we have an error mark module as failed and exit
if (err) {
this.markModuleAsErrored(err);
@@ -1202,9 +1202,9 @@ class NormalModule extends Module {
* @param {Error} e error
* @returns {void}
*/
- const handleParseError = e => {
+ const handleParseError = (e) => {
const source = /** @type {Source} */ (this._source).source();
- const loaders = this.loaders.map(item =>
+ const loaders = this.loaders.map((item) =>
contextify(
/** @type {string} */ (options.context),
item.loader,
@@ -1220,7 +1220,7 @@ class NormalModule extends Module {
const handleParseResult = () => {
this.dependencies.sort(
concatComparators(
- compareSelect(a => a.loc, compareLocations),
+ compareSelect((a) => a.loc, compareLocations),
keepOriginalOrder(this.dependencies)
)
);
@@ -1252,7 +1252,7 @@ class NormalModule extends Module {
/**
* @param {LazySet} deps deps
*/
- const checkDependencies = deps => {
+ const checkDependencies = (deps) => {
for (const dep of deps) {
if (!ABSOLUTE_PATH_REGEX.test(dep)) {
if (nonAbsoluteDependencies === undefined) {
diff --git a/lib/NormalModuleFactory.js b/lib/NormalModuleFactory.js
index c585ace432a..93dc8129b58 100644
--- a/lib/NormalModuleFactory.js
+++ b/lib/NormalModuleFactory.js
@@ -124,7 +124,7 @@ const LEADING_DOT_EXTENSION_REGEX = /^[^.]/;
* @param {LoaderItem} data data
* @returns {string} ident
*/
-const loaderToIdent = data => {
+const loaderToIdent = (data) => {
if (!data.options) {
return data.loader;
}
@@ -158,7 +158,7 @@ const stringifyLoadersAndResource = (loaders, resource) => {
* @param {(err?: null | Error) => void} callback callback
* @returns {(err?: null | Error) => void} callback
*/
-const needCalls = (times, callback) => err => {
+const needCalls = (times, callback) => (err) => {
if (--times === 0) {
return callback(err);
}
@@ -204,7 +204,7 @@ const mergeGlobalOptions = (globalOptions, type, localOptions) => {
* @returns {string} result
*/
const deprecationChangedHookMessage = (name, hook) => {
- const names = hook.taps.map(tapped => tapped.name).join(", ");
+ const names = hook.taps.map((tapped) => tapped.name).join(", ");
return (
`NormalModuleFactory.${name} (${names}) is no longer a waterfall hook, but a bailing hook instead. ` +
@@ -227,7 +227,7 @@ const ruleSetCompiler = new RuleSetCompiler([
new BasicMatcherRulePlugin("issuer"),
new BasicMatcherRulePlugin("compiler"),
new BasicMatcherRulePlugin("issuerLayer"),
- new ObjectMatcherRulePlugin("assert", "assertions", value => {
+ new ObjectMatcherRulePlugin("assert", "assertions", (value) => {
if (value) {
return (
/** @type {ImportAttributes} */ (value)._isLegacyAssert !== undefined
@@ -236,7 +236,7 @@ const ruleSetCompiler = new RuleSetCompiler([
return false;
}),
- new ObjectMatcherRulePlugin("with", "assertions", value => {
+ new ObjectMatcherRulePlugin("with", "assertions", (value) => {
if (value) {
return !(/** @type {ImportAttributes} */ (value)._isLegacyAssert);
}
@@ -498,7 +498,7 @@ class NormalModuleFactory extends ModuleFactory {
)
.split(/!+/);
unresolvedResource = /** @type {string} */ (rawElements.pop());
- elements = rawElements.map(el => {
+ elements = rawElements.map((el) => {
const { path, query } = cachedParseResourceWithoutFragment(el);
return {
loader: path,
@@ -528,7 +528,7 @@ class NormalModuleFactory extends ModuleFactory {
/** @type {undefined | LoaderItem[]} */
let loaders;
- const continueCallback = needCalls(2, err => {
+ const continueCallback = needCalls(2, (err) => {
if (err) return callback(err);
// translate option idents
@@ -656,7 +656,7 @@ class NormalModuleFactory extends ModuleFactory {
/** @type {undefined | LoaderItem[]} */
let preLoaders;
- const continueCallback = needCalls(3, err => {
+ const continueCallback = needCalls(3, (err) => {
if (err) {
return callback(err);
}
@@ -775,7 +775,7 @@ class NormalModuleFactory extends ModuleFactory {
/**
* @param {string} context context
*/
- const defaultResolve = context => {
+ const defaultResolve = (context) => {
if (/^($|\?)/.test(unresolvedResource)) {
resourceData = {
...cacheParseResource(unresolvedResource),
@@ -835,7 +835,7 @@ class NormalModuleFactory extends ModuleFactory {
};
this.hooks.resolveForScheme
.for(scheme)
- .callAsync(resourceData, data, err => {
+ .callAsync(resourceData, data, (err) => {
if (err) return continueCallback(err);
continueCallback();
});
@@ -1016,13 +1016,15 @@ ${hints.join("\n\n")}`;
// Check if the extension is missing a leading dot (e.g. "js" instead of ".js")
let appendResolveExtensionsHint = false;
const specifiedExtensions = [...resolver.options.extensions];
- const expectedExtensions = specifiedExtensions.map(extension => {
- if (LEADING_DOT_EXTENSION_REGEX.test(extension)) {
- appendResolveExtensionsHint = true;
- return `.${extension}`;
+ const expectedExtensions = specifiedExtensions.map(
+ (extension) => {
+ if (LEADING_DOT_EXTENSION_REGEX.test(extension)) {
+ appendResolveExtensionsHint = true;
+ return `.${extension}`;
+ }
+ return extension;
}
- return extension;
- });
+ );
if (appendResolveExtensionsHint) {
err.message += `\nDid you miss the leading dot in 'resolve.extensions'? Did you mean '${JSON.stringify(
expectedExtensions
@@ -1059,7 +1061,7 @@ ${hints.join("\n\n")}`;
) {
asyncLib.parallel(
[
- callback => {
+ (callback) => {
if (!resolver.options.fullySpecified) return callback();
resolver
.withOptions({
@@ -1089,7 +1091,7 @@ Add the extension to the request.`
}
);
},
- callback => {
+ (callback) => {
if (!resolver.options.enforceExtension) return callback();
resolver
.withOptions({
@@ -1128,7 +1130,7 @@ Including the extension in the request is no longer possible. Did you mean to en
}
);
},
- callback => {
+ (callback) => {
if (
/^\.\.?\//.test(unresolvedResource) ||
resolver.options.preferRelative
@@ -1143,7 +1145,7 @@ Including the extension in the request is no longer possible. Did you mean to en
(err, resolvedResource) => {
if (err || !resolvedResource) return callback();
const moduleDirectories = resolver.options.modules
- .map(m => (Array.isArray(m) ? m.join(", ") : m))
+ .map((m) => (Array.isArray(m) ? m.join(", ") : m))
.join(", ");
callback(
null,
@@ -1201,7 +1203,7 @@ If changing the source code is not an option there is also a resolve options cal
context,
`${item.loader}-loader`,
resolveContext,
- err2 => {
+ (err2) => {
if (!err2) {
err.message =
`${err.message}\n` +
diff --git a/lib/NormalModuleReplacementPlugin.js b/lib/NormalModuleReplacementPlugin.js
index 80206f26ac0..aa7eea7d6a2 100644
--- a/lib/NormalModuleReplacementPlugin.js
+++ b/lib/NormalModuleReplacementPlugin.js
@@ -34,8 +34,8 @@ class NormalModuleReplacementPlugin {
apply(compiler) {
const resourceRegExp = this.resourceRegExp;
const newResource = this.newResource;
- compiler.hooks.normalModuleFactory.tap(PLUGIN_NAME, nmf => {
- nmf.hooks.beforeResolve.tap(PLUGIN_NAME, result => {
+ compiler.hooks.normalModuleFactory.tap(PLUGIN_NAME, (nmf) => {
+ nmf.hooks.beforeResolve.tap(PLUGIN_NAME, (result) => {
if (resourceRegExp.test(result.request)) {
if (typeof newResource === "function") {
newResource(result);
@@ -44,7 +44,7 @@ class NormalModuleReplacementPlugin {
}
}
});
- nmf.hooks.afterResolve.tap(PLUGIN_NAME, result => {
+ nmf.hooks.afterResolve.tap(PLUGIN_NAME, (result) => {
const createData = result.createData;
if (resourceRegExp.test(/** @type {string} */ (createData.resource))) {
if (typeof newResource === "function") {
diff --git a/lib/PrefetchPlugin.js b/lib/PrefetchPlugin.js
index ce5d802ef5d..52cf9647bb1 100644
--- a/lib/PrefetchPlugin.js
+++ b/lib/PrefetchPlugin.js
@@ -45,7 +45,7 @@ class PrefetchPlugin {
compilation.addModuleChain(
this.context || compiler.context,
new PrefetchDependency(this.request),
- err => {
+ (err) => {
callback(err);
}
);
diff --git a/lib/ProgressPlugin.js b/lib/ProgressPlugin.js
index 65d6dacd173..9577f93a81f 100644
--- a/lib/ProgressPlugin.js
+++ b/lib/ProgressPlugin.js
@@ -74,7 +74,7 @@ const createDefaultHandler = (profile, logger) => {
lastStateInfo.length = 0;
}
const fullState = [msg, ...args];
- const state = fullState.map(s => s.replace(/\d+\/\d+ /g, ""));
+ const state = fullState.map((s) => s.replace(/\d+\/\d+ /g, ""));
const now = Date.now();
const len = Math.max(state.length, lastStateInfo.length);
for (let i = len; i >= 0; i--) {
@@ -354,7 +354,7 @@ class ProgressPlugin {
/**
* @param {Module} module the module
*/
- const moduleBuild = module => {
+ const moduleBuild = (module) => {
const ident = module.identifier();
if (ident) {
activeModules.add(ident);
@@ -375,7 +375,7 @@ class ProgressPlugin {
/**
* @param {Module} module the module
*/
- const moduleDone = module => {
+ const moduleDone = (module) => {
doneModules++;
if (showActiveModules) {
const ident = module.identifier();
@@ -411,7 +411,7 @@ class ProgressPlugin {
compiler.hooks.beforeCompile.tap(PLUGIN_NAME, () => {
if (!cacheGetPromise) {
cacheGetPromise = cache.getPromise().then(
- data => {
+ (data) => {
if (data) {
lastModulesCount = lastModulesCount || data.modulesCount;
lastDependenciesCount =
@@ -419,17 +419,17 @@ class ProgressPlugin {
}
return data;
},
- _err => {
+ (_err) => {
// Ignore error
}
);
}
});
- compiler.hooks.afterCompile.tapPromise(PLUGIN_NAME, compilation => {
+ compiler.hooks.afterCompile.tapPromise(PLUGIN_NAME, (compilation) => {
if (compilation.compiler.isChild()) return Promise.resolve();
return /** @type {Promise} */ (cacheGetPromise).then(
- async oldData => {
+ async (oldData) => {
const realModulesCount = modulesCount - skippedModulesCount;
const realDependenciesCount =
dependenciesCount - skippedDependenciesCount;
@@ -448,7 +448,7 @@ class ProgressPlugin {
);
});
- compiler.hooks.compilation.tap(PLUGIN_NAME, compilation => {
+ compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
if (compilation.compiler.isChild()) return;
lastModulesCount = modulesCount;
lastEntriesCount = entriesCount;
@@ -461,12 +461,12 @@ class ProgressPlugin {
0;
doneModules = doneDependencies = doneEntries = 0;
- compilation.factorizeQueue.hooks.added.tap(PLUGIN_NAME, item =>
+ compilation.factorizeQueue.hooks.added.tap(PLUGIN_NAME, (item) =>
factorizeAdd(compilation.factorizeQueue, item)
);
compilation.factorizeQueue.hooks.result.tap(PLUGIN_NAME, factorizeDone);
- compilation.addModuleQueue.hooks.added.tap(PLUGIN_NAME, item =>
+ compilation.addModuleQueue.hooks.added.tap(PLUGIN_NAME, (item) =>
moduleAdd(compilation.addModuleQueue, item)
);
compilation.processDependenciesQueue.hooks.result.tap(
@@ -487,7 +487,7 @@ class ProgressPlugin {
const requiredLoaders = new Set();
NormalModule.getCompilationHooks(compilation).beforeLoaders.tap(
PLUGIN_NAME,
- loaders => {
+ (loaders) => {
for (const loader of loaders) {
if (
loader.type !== "module" &&
diff --git a/lib/ProvidePlugin.js b/lib/ProvidePlugin.js
index dbf98a69a41..898bd0d0847 100644
--- a/lib/ProvidePlugin.js
+++ b/lib/ProvidePlugin.js
@@ -74,7 +74,7 @@ class ProvidePlugin {
}
}
- parser.hooks.expression.for(name).tap(PLUGIN_NAME, expr => {
+ parser.hooks.expression.for(name).tap(PLUGIN_NAME, (expr) => {
const nameIdentifier = name.includes(".")
? `__webpack_provided_${name.replace(/\./g, "_dot_")}`
: name;
@@ -89,7 +89,7 @@ class ProvidePlugin {
return true;
});
- parser.hooks.call.for(name).tap(PLUGIN_NAME, expr => {
+ parser.hooks.call.for(name).tap(PLUGIN_NAME, (expr) => {
const nameIdentifier = name.includes(".")
? `__webpack_provided_${name.replace(/\./g, "_dot_")}`
: name;
diff --git a/lib/RecordIdsPlugin.js b/lib/RecordIdsPlugin.js
index f3e11443905..fa7cb8ce2db 100644
--- a/lib/RecordIdsPlugin.js
+++ b/lib/RecordIdsPlugin.js
@@ -63,14 +63,14 @@ class RecordIdsPlugin {
* @param {Module} module the module
* @returns {string} the (portable) identifier
*/
- const getModuleIdentifier = module => {
+ const getModuleIdentifier = (module) => {
if (portableIds) {
return makePathsRelative(module.identifier());
}
return module.identifier();
};
- compiler.hooks.compilation.tap(PLUGIN_NAME, compilation => {
+ compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
compilation.hooks.recordModules.tap(PLUGIN_NAME, (modules, records) => {
const chunkGraph = compilation.chunkGraph;
if (!records.modules) records.modules = {};
@@ -112,7 +112,7 @@ class RecordIdsPlugin {
* @param {Chunk} chunk the chunk
* @returns {string[]} sources of the chunk
*/
- const getChunkSources = chunk => {
+ const getChunkSources = (chunk) => {
/** @type {string[]} */
const sources = [];
for (const chunkGroup of chunk.groupsIterable) {
diff --git a/lib/ResolverFactory.js b/lib/ResolverFactory.js
index 61bb42ebd89..697fdee5c16 100644
--- a/lib/ResolverFactory.js
+++ b/lib/ResolverFactory.js
@@ -36,7 +36,7 @@ const EMPTY_RESOLVE_OPTIONS = {};
* @param {ResolveOptionsWithDependencyType} resolveOptionsWithDepType enhanced options
* @returns {ResolveOptions} merged options
*/
-const convertToResolveOptions = resolveOptionsWithDepType => {
+const convertToResolveOptions = (resolveOptionsWithDepType) => {
const { dependencyType, plugins, ...remaining } = resolveOptionsWithDepType;
// check type compat
@@ -46,7 +46,7 @@ const convertToResolveOptions = resolveOptionsWithDepType => {
plugins:
plugins &&
/** @type {ResolvePluginInstance[]} */ (
- plugins.filter(item => item !== "...")
+ plugins.filter((item) => item !== "...")
)
};
@@ -142,7 +142,7 @@ module.exports = class ResolverFactory {
}
/** @type {WeakMap, ResolverWithOptions>} */
const childCache = new WeakMap();
- resolver.withOptions = options => {
+ resolver.withOptions = (options) => {
const cacheEntry = childCache.get(options);
if (cacheEntry !== undefined) return cacheEntry;
const mergedOptions = cachedCleverMerge(originalResolveOptions, options);
diff --git a/lib/RuntimeGlobals.js b/lib/RuntimeGlobals.js
index 753d6891ea4..26178a0e5df 100644
--- a/lib/RuntimeGlobals.js
+++ b/lib/RuntimeGlobals.js
@@ -109,6 +109,26 @@ module.exports.ensureChunkIncludeEntries =
*/
module.exports.entryModuleId = "__webpack_require__.s";
+/**
+ * esm module id
+ */
+module.exports.esmId = "__webpack_esm_id__";
+
+/**
+ * esm module ids
+ */
+module.exports.esmIds = "__webpack_esm_ids__";
+
+/**
+ * esm modules
+ */
+module.exports.esmModules = "__webpack_esm_modules__";
+
+/**
+ * esm runtime
+ */
+module.exports.esmRuntime = "__webpack_esm_runtime__";
+
/**
* the internal exports object
*/
diff --git a/lib/RuntimePlugin.js b/lib/RuntimePlugin.js
index d4eeb5b86da..6e9e30959bb 100644
--- a/lib/RuntimePlugin.js
+++ b/lib/RuntimePlugin.js
@@ -118,13 +118,13 @@ class RuntimePlugin {
* @returns {void}
*/
apply(compiler) {
- compiler.hooks.compilation.tap(PLUGIN_NAME, compilation => {
+ compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
const globalChunkLoading = compilation.outputOptions.chunkLoading;
/**
* @param {Chunk} chunk chunk
* @returns {boolean} true, when chunk loading is disabled for the chunk
*/
- const isChunkLoadingDisabledForChunk = chunk => {
+ const isChunkLoadingDisabledForChunk = (chunk) => {
const options = chunk.getEntryOptions();
const chunkLoading =
options && options.chunkLoading !== undefined
@@ -168,7 +168,7 @@ class RuntimePlugin {
}
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.definePropertyGetters)
- .tap(PLUGIN_NAME, chunk => {
+ .tap(PLUGIN_NAME, (chunk) => {
compilation.addRuntimeModule(
chunk,
new DefinePropertyGettersRuntimeModule()
@@ -177,7 +177,7 @@ class RuntimePlugin {
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.makeNamespaceObject)
- .tap(PLUGIN_NAME, chunk => {
+ .tap(PLUGIN_NAME, (chunk) => {
compilation.addRuntimeModule(
chunk,
new MakeNamespaceObjectRuntimeModule()
@@ -186,7 +186,7 @@ class RuntimePlugin {
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.createFakeNamespaceObject)
- .tap(PLUGIN_NAME, chunk => {
+ .tap(PLUGIN_NAME, (chunk) => {
compilation.addRuntimeModule(
chunk,
new CreateFakeNamespaceObjectRuntimeModule()
@@ -206,7 +206,7 @@ class RuntimePlugin {
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.hasOwnProperty)
- .tap(PLUGIN_NAME, chunk => {
+ .tap(PLUGIN_NAME, (chunk) => {
compilation.addRuntimeModule(
chunk,
new HasOwnPropertyRuntimeModule()
@@ -215,7 +215,7 @@ class RuntimePlugin {
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.compatGetDefaultExport)
- .tap(PLUGIN_NAME, chunk => {
+ .tap(PLUGIN_NAME, (chunk) => {
compilation.addRuntimeModule(
chunk,
new CompatGetDefaultExportRuntimeModule()
@@ -224,7 +224,7 @@ class RuntimePlugin {
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.runtimeId)
- .tap(PLUGIN_NAME, chunk => {
+ .tap(PLUGIN_NAME, (chunk) => {
compilation.addRuntimeModule(chunk, new RuntimeIdRuntimeModule());
return true;
});
@@ -259,13 +259,13 @@ class RuntimePlugin {
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.global)
- .tap(PLUGIN_NAME, chunk => {
+ .tap(PLUGIN_NAME, (chunk) => {
compilation.addRuntimeModule(chunk, new GlobalRuntimeModule());
return true;
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.asyncModule)
- .tap(PLUGIN_NAME, chunk => {
+ .tap(PLUGIN_NAME, (chunk) => {
const experiments = compilation.options.experiments;
compilation.addRuntimeModule(
chunk,
@@ -275,7 +275,7 @@ class RuntimePlugin {
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.systemContext)
- .tap(PLUGIN_NAME, chunk => {
+ .tap(PLUGIN_NAME, (chunk) => {
const entryOptions = chunk.getEntryOptions();
const libraryType =
entryOptions && entryOptions.library !== undefined
@@ -308,7 +308,7 @@ class RuntimePlugin {
"javascript",
"javascript",
RuntimeGlobals.getChunkScriptFilename,
- chunk =>
+ (chunk) =>
getJavascriptModulesPlugin().chunkHasJs(chunk, chunkGraph) &&
/** @type {TemplatePath} */ (
chunk.filenameTemplate ||
@@ -338,7 +338,7 @@ class RuntimePlugin {
"css",
"css",
RuntimeGlobals.getChunkCssFilename,
- chunk =>
+ (chunk) =>
getCssModulesPlugin().chunkHasCss(chunk, chunkGraph) &&
getChunkFilenameTemplate(chunk, compilation.outputOptions),
set.has(RuntimeGlobals.hmrDownloadUpdateHandlers)
@@ -363,7 +363,7 @@ class RuntimePlugin {
"javascript",
"javascript update",
RuntimeGlobals.getChunkUpdateScriptFilename,
- _chunk =>
+ (_chunk) =>
/** @type {NonNullable} */
(compilation.outputOptions.hotUpdateChunkFilename),
true
@@ -480,7 +480,7 @@ class RuntimePlugin {
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.baseURI)
- .tap(PLUGIN_NAME, chunk => {
+ .tap(PLUGIN_NAME, (chunk) => {
if (isChunkLoadingDisabledForChunk(chunk)) {
compilation.addRuntimeModule(chunk, new BaseUriRuntimeModule());
return true;
@@ -488,7 +488,7 @@ class RuntimePlugin {
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.scriptNonce)
- .tap(PLUGIN_NAME, chunk => {
+ .tap(PLUGIN_NAME, (chunk) => {
compilation.addRuntimeModule(chunk, new NonceRuntimeModule());
return true;
});
diff --git a/lib/RuntimeTemplate.js b/lib/RuntimeTemplate.js
index ac1b2d358b3..bc5c4cf9015 100644
--- a/lib/RuntimeTemplate.js
+++ b/lib/RuntimeTemplate.js
@@ -49,12 +49,12 @@ This should not happen.
It's in these chunks: ${
Array.from(
chunkGraph.getModuleChunksIterable(module),
- c => c.name || c.id || c.debugId
+ (c) => c.name || c.id || c.debugId
).join(", ") || "none"
} (If module is in no chunk this indicates a bug in some chunk/module optimization logic)
Module has these incoming connections: ${Array.from(
chunkGraph.moduleGraph.getIncomingConnections(module),
- connection =>
+ (connection) =>
`\n - ${
connection.originModule && connection.originModule.identifier()
} ${connection.dependency && connection.dependency.type} ${
@@ -162,6 +162,16 @@ class RuntimeTemplate {
return this.outputOptions.environment.nodePrefixForCoreModules;
}
+ /**
+ * @param {string} mod a module
+ * @returns {string} a module with `node:` prefix when supported, otherwise an original name
+ */
+ renderNodePrefixForCoreModule(mod) {
+ return this.outputOptions.environment.nodePrefixForCoreModules
+ ? `"node:${mod}"`
+ : `"${mod}"`;
+ }
+
/**
* @param {string} returnValue return value
* @param {string} args arguments
@@ -229,7 +239,7 @@ class RuntimeTemplate {
if (concatenationCost <= templateCost) return this._es5Concatenation(args);
return `\`${args
- .map(arg => (typeof arg === "string" ? arg : `\${${arg.expr}}`))
+ .map((arg) => (typeof arg === "string" ? arg : `\${${arg.expr}}`))
.join("")}\``;
}
@@ -240,7 +250,7 @@ class RuntimeTemplate {
*/
_es5Concatenation(args) {
const str = args
- .map(arg => (typeof arg === "string" ? JSON.stringify(arg) : arg.expr))
+ .map((arg) => (typeof arg === "string" ? JSON.stringify(arg) : arg.expr))
.join(" + ");
// when the first two args are expression, we need to prepend "" + to force string
@@ -290,7 +300,9 @@ class RuntimeTemplate {
return this.supportsDestructuring()
? `var {${items.join(", ")}} = ${value};`
: Template.asString(
- items.map(item => `var ${item} = ${value}${propertyAccess([item])};`)
+ items.map(
+ (item) => `var ${item} = ${value}${propertyAccess([item])};`
+ )
);
}
@@ -332,12 +344,12 @@ class RuntimeTemplate {
if (this.outputOptions.pathinfo) {
content = [message, request, chunkName, chunkReason]
.filter(Boolean)
- .map(item => this.requestShortener.shorten(item))
+ .map((item) => this.requestShortener.shorten(item))
.join(" | ");
} else {
content = [message, chunkName, chunkReason]
.filter(Boolean)
- .map(item => this.requestShortener.shorten(item))
+ .map((item) => this.requestShortener.shorten(item))
.join(" | ");
}
if (!content) return "";
@@ -763,14 +775,14 @@ class RuntimeTemplate {
if (typeof runtimeCondition === "boolean") return `${runtimeCondition}`;
/** @type {Set} */
const positiveRuntimeIds = new Set();
- forEachRuntime(runtimeCondition, runtime =>
+ forEachRuntime(runtimeCondition, (runtime) =>
positiveRuntimeIds.add(
`${chunkGraph.getRuntimeId(/** @type {string} */ (runtime))}`
)
);
/** @type {Set} */
const negativeRuntimeIds = new Set();
- forEachRuntime(subtractRuntime(runtime, runtimeCondition), runtime =>
+ forEachRuntime(subtractRuntime(runtime, runtimeCondition), (runtime) =>
negativeRuntimeIds.add(
`${chunkGraph.getRuntimeId(/** @type {string} */ (runtime))}`
)
@@ -817,13 +829,6 @@ class RuntimeTemplate {
];
}
- defer = defer && (module.buildMeta ? !module.buildMeta.async : true);
-
- /** @type {Set} */
- const outgoingAsyncModules = defer
- ? getOutgoingAsyncModules(moduleGraph, module)
- : new Set();
-
if (chunkGraph.getModuleId(module) === null) {
if (weak) {
// only weak referenced modules don't get an id
@@ -860,12 +865,15 @@ class RuntimeTemplate {
);
runtimeRequirements.add(RuntimeGlobals.require);
let importContent;
- if (defer) {
+ if (defer && !(/** @type {BuildMeta} */ (module.buildMeta).async)) {
+ /** @type {Set} */
+ const outgoingAsyncModules = getOutgoingAsyncModules(moduleGraph, module);
+
importContent = `/* deferred harmony import */ ${optDeclaration}${importVar} = ${getOptimizedDeferredModule(
this,
exportsType,
moduleId,
- Array.from(outgoingAsyncModules, mod => chunkGraph.getModuleId(mod))
+ Array.from(outgoingAsyncModules, (mod) => chunkGraph.getModuleId(mod))
)};\n`;
return [importContent, ""];
@@ -924,8 +932,6 @@ class RuntimeTemplate {
request
});
}
-
- defer = defer && (module.buildMeta ? !module.buildMeta.async : true);
if (!Array.isArray(exportName)) {
exportName = exportName ? [exportName] : [];
}
@@ -935,10 +941,13 @@ class RuntimeTemplate {
(originModule.buildMeta).strictHarmonyModule
);
+ const isDeferred =
+ defer && !(/** @type {BuildMeta} */ (module.buildMeta).async);
+
if (defaultInterop) {
// when the defaultInterop is used (when a ESM imports a CJS module),
if (exportName.length > 0 && exportName[0] === "default") {
- if (defer && exportsType !== "namespace") {
+ if (isDeferred && exportsType !== "namespace") {
const access = `${importVar}.a${propertyAccess(exportName, 1)}`;
if (isCall || asiSafe === undefined) {
return access;
@@ -983,7 +992,7 @@ class RuntimeTemplate {
) {
return "/* __esModule */true";
}
- } else if (defer) {
+ } else if (isDeferred) {
// now exportName.length is 0
// fall through to the end of this function, create the namespace there.
} else if (
@@ -1026,7 +1035,7 @@ class RuntimeTemplate {
? ""
: `${Template.toNormalComment(propertyAccess(exportName))} `;
const access = `${importVar}${
- defer ? ".a" : ""
+ isDeferred ? ".a" : ""
}${comment}${propertyAccess(used)}`;
if (isCall && callContext === false) {
return asiSafe
@@ -1037,7 +1046,7 @@ class RuntimeTemplate {
}
return access;
}
- if (defer) {
+ if (isDeferred) {
initFragments.push(
new InitFragment(
`var ${importVar}_deferred_namespace_cache;\n`,
@@ -1087,7 +1096,7 @@ class RuntimeTemplate {
return `Promise.resolve(${comment.trim()})`;
}
const chunks = chunkGroup.chunks.filter(
- chunk => !chunk.hasRuntime() && chunk.id !== null
+ (chunk) => !chunk.hasRuntime() && chunk.id !== null
);
const comment = this.comment({
message,
@@ -1119,7 +1128,7 @@ class RuntimeTemplate {
* @param {Chunk} chunk chunk
* @returns {string} require chunk id code
*/
- const requireChunkId = chunk =>
+ const requireChunkId = (chunk) =>
`${RuntimeGlobals.ensureChunk}(${JSON.stringify(chunk.id)}${
fetchPriority ? `, ${JSON.stringify(fetchPriority)}` : ""
})`;
diff --git a/lib/SizeFormatHelpers.js b/lib/SizeFormatHelpers.js
index 4c6a748f0eb..e233d5fa630 100644
--- a/lib/SizeFormatHelpers.js
+++ b/lib/SizeFormatHelpers.js
@@ -9,7 +9,7 @@
* @param {number} size the size in bytes
* @returns {string} the formatted size
*/
-module.exports.formatSize = size => {
+module.exports.formatSize = (size) => {
if (typeof size !== "number" || Number.isNaN(size) === true) {
return "unknown size";
}
diff --git a/lib/SourceMapDevToolModuleOptionsPlugin.js b/lib/SourceMapDevToolModuleOptionsPlugin.js
index ae62b0379aa..c024125bd7a 100644
--- a/lib/SourceMapDevToolModuleOptionsPlugin.js
+++ b/lib/SourceMapDevToolModuleOptionsPlugin.js
@@ -27,17 +27,17 @@ class SourceMapDevToolModuleOptionsPlugin {
apply(compilation) {
const options = this.options;
if (options.module !== false) {
- compilation.hooks.buildModule.tap(PLUGIN_NAME, module => {
+ compilation.hooks.buildModule.tap(PLUGIN_NAME, (module) => {
module.useSourceMap = true;
});
- compilation.hooks.runtimeModule.tap(PLUGIN_NAME, module => {
+ compilation.hooks.runtimeModule.tap(PLUGIN_NAME, (module) => {
module.useSourceMap = true;
});
} else {
- compilation.hooks.buildModule.tap(PLUGIN_NAME, module => {
+ compilation.hooks.buildModule.tap(PLUGIN_NAME, (module) => {
module.useSimpleSourceMap = true;
});
- compilation.hooks.runtimeModule.tap(PLUGIN_NAME, module => {
+ compilation.hooks.runtimeModule.tap(PLUGIN_NAME, (module) => {
module.useSimpleSourceMap = true;
});
}
diff --git a/lib/SourceMapDevToolPlugin.js b/lib/SourceMapDevToolPlugin.js
index f5f28efd533..913dad02730 100644
--- a/lib/SourceMapDevToolPlugin.js
+++ b/lib/SourceMapDevToolPlugin.js
@@ -65,7 +65,7 @@ const URL_FORMATTING_REGEXP = /^\n\/\/(.*)$/;
* @param {RegExp} regexp Stateful Regular Expression to be reset
* @returns {void}
*/
-const resetRegexpState = regexp => {
+const resetRegexpState = (regexp) => {
regexp.lastIndex = -1;
};
@@ -74,7 +74,7 @@ const resetRegexpState = regexp => {
* @param {string} str String to quote
* @returns {string} Escaped string
*/
-const quoteMeta = str => str.replace(METACHARACTERS_REGEXP, "\\$&");
+const quoteMeta = (str) => str.replace(METACHARACTERS_REGEXP, "\\$&");
/**
* Creating {@link SourceMapTask} for given file
@@ -112,7 +112,7 @@ const getTaskForFile = (
const context = /** @type {string} */ (compilation.options.context);
const root = compilation.compiler.root;
const cachedAbsolutify = makePathsAbsolute.bindContextCache(context, root);
- const modules = sourceMap.sources.map(source => {
+ const modules = sourceMap.sources.map((source) => {
if (!source.startsWith("webpack://")) return source;
source = cachedAbsolutify(source.slice(10));
const module = compilation.findModule(source);
@@ -179,7 +179,7 @@ class SourceMapDevToolPlugin {
options
);
- compiler.hooks.compilation.tap(PLUGIN_NAME, compilation => {
+ compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
new SourceMapDevToolModuleOptionsPlugin(options).apply(compilation);
compilation.hooks.processAssets.tapAsync(
@@ -348,7 +348,7 @@ class SourceMapDevToolPlugin {
callback();
});
},
- err => {
+ (err) => {
if (err) {
return callback(err);
}
@@ -431,7 +431,7 @@ class SourceMapDevToolPlugin {
"attach SourceMap"
);
- const moduleFilenames = modules.map(m =>
+ const moduleFilenames = modules.map((m) =>
moduleToSourceNameMapping.get(m)
);
sourceMap.sources = /** @type {string[]} */ (moduleFilenames);
@@ -454,7 +454,7 @@ class SourceMapDevToolPlugin {
: quoteMeta(contenthash);
sourceMap.file = sourceMap.file.replace(
new RegExp(pattern, "g"),
- m => "x".repeat(m.length)
+ (m) => "x".repeat(m.length)
);
}
@@ -584,7 +584,7 @@ class SourceMapDevToolPlugin {
compilation.updateAsset(file, asset);
}
- task.cacheItem.store({ assets, assetsInfo }, err => {
+ task.cacheItem.store({ assets, assetsInfo }, (err) => {
reportProgress(
0.5 + (0.5 * ++taskIndex) / tasks.length,
task.file,
@@ -597,7 +597,7 @@ class SourceMapDevToolPlugin {
callback();
});
},
- err => {
+ (err) => {
reportProgress(1);
callback(err);
}
diff --git a/lib/Stats.js b/lib/Stats.js
index 22a36632a97..2a883796269 100644
--- a/lib/Stats.js
+++ b/lib/Stats.js
@@ -36,7 +36,7 @@ class Stats {
hasWarnings() {
return (
this.compilation.getWarnings().length > 0 ||
- this.compilation.children.some(child => child.getStats().hasWarnings())
+ this.compilation.children.some((child) => child.getStats().hasWarnings())
);
}
@@ -46,7 +46,7 @@ class Stats {
hasErrors() {
return (
this.compilation.errors.length > 0 ||
- this.compilation.children.some(child => child.getStats().hasErrors())
+ this.compilation.children.some((child) => child.getStats().hasErrors())
);
}
diff --git a/lib/Template.js b/lib/Template.js
index 9b91ac0f040..f8b60e3becb 100644
--- a/lib/Template.js
+++ b/lib/Template.js
@@ -296,7 +296,7 @@ class Template {
return null;
}
/** @type {{id: string|number, source: Source|string}[]} */
- const allModules = modules.map(module => ({
+ const allModules = modules.map((module) => ({
id: /** @type {ModuleId} */ (chunkGraph.getModuleId(module)),
source: renderModule(module) || "false"
}));
diff --git a/lib/TemplatedPathPlugin.js b/lib/TemplatedPathPlugin.js
index 3439bfd4b46..0afb5aff26a 100644
--- a/lib/TemplatedPathPlugin.js
+++ b/lib/TemplatedPathPlugin.js
@@ -24,7 +24,7 @@ const REGEXP = /\[\\*([\w:]+)\\*\]/gi;
* @param {string | number} id id
* @returns {string | number} result
*/
-const prepareId = id => {
+const prepareId = (id) => {
if (typeof id !== "string") return id;
if (/^"\s\+*.*\+\s*"$/.test(id)) {
@@ -389,7 +389,7 @@ class TemplatedPathPlugin {
* @returns {void}
*/
apply(compiler) {
- compiler.hooks.compilation.tap(plugin, compilation => {
+ compiler.hooks.compilation.tap(plugin, (compilation) => {
compilation.hooks.assetPath.tap(plugin, replacePathVariables);
});
}
diff --git a/lib/UseStrictPlugin.js b/lib/UseStrictPlugin.js
index 3db3daa8f62..ea1d87fbebb 100644
--- a/lib/UseStrictPlugin.js
+++ b/lib/UseStrictPlugin.js
@@ -36,7 +36,7 @@ class UseStrictPlugin {
* @param {JavascriptParserOptions} parserOptions the javascript parser options
*/
const handler = (parser, parserOptions) => {
- parser.hooks.program.tap(PLUGIN_NAME, ast => {
+ parser.hooks.program.tap(PLUGIN_NAME, (ast) => {
const firstNode = ast.body[0];
if (
firstNode &&
diff --git a/lib/WarnCaseSensitiveModulesPlugin.js b/lib/WarnCaseSensitiveModulesPlugin.js
index 5badc2229c4..a272cff0503 100644
--- a/lib/WarnCaseSensitiveModulesPlugin.js
+++ b/lib/WarnCaseSensitiveModulesPlugin.js
@@ -20,7 +20,7 @@ class WarnCaseSensitiveModulesPlugin {
* @returns {void}
*/
apply(compiler) {
- compiler.hooks.compilation.tap(PLUGIN_NAME, compilation => {
+ compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
compilation.hooks.seal.tap(PLUGIN_NAME, () => {
/** @type {Map>} */
const moduleWithoutCase = new Map();
diff --git a/lib/WarnDeprecatedOptionPlugin.js b/lib/WarnDeprecatedOptionPlugin.js
index 96183768788..5afe80e9c19 100644
--- a/lib/WarnDeprecatedOptionPlugin.js
+++ b/lib/WarnDeprecatedOptionPlugin.js
@@ -30,7 +30,7 @@ class WarnDeprecatedOptionPlugin {
* @returns {void}
*/
apply(compiler) {
- compiler.hooks.thisCompilation.tap(PLUGIN_NAME, compilation => {
+ compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {
compilation.warnings.push(
new DeprecatedOptionWarning(this.option, this.value, this.suggestion)
);
diff --git a/lib/WarnNoModeSetPlugin.js b/lib/WarnNoModeSetPlugin.js
index 7eaee450bc4..3eaae89bc34 100644
--- a/lib/WarnNoModeSetPlugin.js
+++ b/lib/WarnNoModeSetPlugin.js
@@ -18,7 +18,7 @@ class WarnNoModeSetPlugin {
* @returns {void}
*/
apply(compiler) {
- compiler.hooks.thisCompilation.tap(PLUGIN_NAME, compilation => {
+ compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {
compilation.warnings.push(new NoModeWarning());
});
}
diff --git a/lib/WatchIgnorePlugin.js b/lib/WatchIgnorePlugin.js
index 0840575fc23..b47b1cdefd6 100644
--- a/lib/WatchIgnorePlugin.js
+++ b/lib/WatchIgnorePlugin.js
@@ -45,8 +45,8 @@ class IgnoringWatchFileSystem {
* @param {string} path path to check
* @returns {boolean} true, if path is ignored
*/
- const ignored = path =>
- this.paths.some(p =>
+ const ignored = (path) =>
+ this.paths.some((p) =>
p instanceof RegExp ? p.test(path) : path.indexOf(p) === 0
);
diff --git a/lib/Watching.js b/lib/Watching.js
index a047f257b20..c3e9bc915bf 100644
--- a/lib/Watching.js
+++ b/lib/Watching.js
@@ -159,14 +159,14 @@ class Watching {
const run = () => {
if (this.compiler.idle) {
- return this.compiler.cache.endIdle(err => {
+ return this.compiler.cache.endIdle((err) => {
if (err) return this._done(err);
this.compiler.idle = false;
run();
});
}
if (this._needRecords) {
- return this.compiler.readRecords(err => {
+ return this.compiler.readRecords((err) => {
if (err) return this._done(err);
this._needRecords = false;
@@ -175,7 +175,7 @@ class Watching {
}
this.invalid = false;
this._invalidReported = false;
- this.compiler.hooks.watchRun.callAsync(this.compiler, err => {
+ this.compiler.hooks.watchRun.callAsync(this.compiler, (err) => {
if (err) return this._done(err);
/**
* @param {Error | null} err error
@@ -196,13 +196,13 @@ class Watching {
process.nextTick(() => {
const logger = compilation.getLogger("webpack.Compiler");
logger.time("emitAssets");
- this.compiler.emitAssets(compilation, err => {
+ this.compiler.emitAssets(compilation, (err) => {
logger.timeEnd("emitAssets");
if (err) return this._done(err, compilation);
if (this.invalid) return this._done(null, compilation);
logger.time("emitRecords");
- this.compiler.emitRecords(err => {
+ this.compiler.emitRecords((err) => {
logger.timeEnd("emitRecords");
if (err) return this._done(err, compilation);
@@ -215,11 +215,11 @@ class Watching {
compilation.endTime = Date.now();
logger.time("done hook");
const stats = new Stats(compilation);
- this.compiler.hooks.done.callAsync(stats, err => {
+ this.compiler.hooks.done.callAsync(stats, (err) => {
logger.timeEnd("done hook");
if (err) return this._done(err, compilation);
- this.compiler.hooks.additionalPass.callAsync(err => {
+ this.compiler.hooks.additionalPass.callAsync((err) => {
if (err) return this._done(err, compilation);
this.compiler.compile(onCompiled);
});
@@ -288,7 +288,7 @@ class Watching {
logger.time("storeBuildDependencies");
this.compiler.cache.storeBuildDependencies(
compilation.buildDependencies,
- err => {
+ (err) => {
logger.timeEnd("storeBuildDependencies");
if (err) return handleError(err);
this._go();
@@ -311,7 +311,7 @@ class Watching {
const cbs = this.callbacks;
this.callbacks = [];
logger.time("done hook");
- this.compiler.hooks.done.callAsync(/** @type {Stats} */ (stats), err => {
+ this.compiler.hooks.done.callAsync(/** @type {Stats} */ (stats), (err) => {
logger.timeEnd("done hook");
if (err) return handleError(err, cbs);
this.handler(null, stats);
@@ -319,7 +319,7 @@ class Watching {
this.compiler.cache.storeBuildDependencies(
/** @type {Compilation} */
(compilation).buildDependencies,
- err => {
+ (err) => {
logger.timeEnd("storeBuildDependencies");
if (err) return handleError(err, cbs);
logger.time("beginIdle");
@@ -480,7 +480,7 @@ class Watching {
/**
* @param {WebpackError | null} err error if any
*/
- const shutdown = err => {
+ const shutdown = (err) => {
this.compiler.hooks.watchClose.call();
const closeCallbacks =
/** @type {Callback[]} */
@@ -493,7 +493,7 @@ class Watching {
logger.time("storeBuildDependencies");
this.compiler.cache.storeBuildDependencies(
compilation.buildDependencies,
- err2 => {
+ (err2) => {
logger.timeEnd("storeBuildDependencies");
shutdown(err || err2);
}
diff --git a/lib/WebpackIsIncludedPlugin.js b/lib/WebpackIsIncludedPlugin.js
index 4b18790b2e5..3625901147d 100644
--- a/lib/WebpackIsIncludedPlugin.js
+++ b/lib/WebpackIsIncludedPlugin.js
@@ -47,10 +47,10 @@ class WebpackIsIncludedPlugin {
* @param {JavascriptParser} parser the parser
* @returns {void}
*/
- const handler = parser => {
+ const handler = (parser) => {
parser.hooks.call
.for("__webpack_is_included__")
- .tap(PLUGIN_NAME, expr => {
+ .tap(PLUGIN_NAME, (expr) => {
if (
expr.type !== "CallExpression" ||
expr.arguments.length !== 1 ||
diff --git a/lib/WebpackOptionsApply.js b/lib/WebpackOptionsApply.js
index 9ebdaa6dc91..906451d35ca 100644
--- a/lib/WebpackOptionsApply.js
+++ b/lib/WebpackOptionsApply.js
@@ -858,7 +858,7 @@ class WebpackOptionsApply extends OptionsApply {
}
compiler.resolverFactory.hooks.resolveOptions
.for("normal")
- .tap(CLASS_NAME, resolveOptions => {
+ .tap(CLASS_NAME, (resolveOptions) => {
resolveOptions = cleverMerge(options.resolve, resolveOptions);
resolveOptions.fileSystem =
/** @type {InputFileSystem} */
@@ -867,7 +867,7 @@ class WebpackOptionsApply extends OptionsApply {
});
compiler.resolverFactory.hooks.resolveOptions
.for("context")
- .tap(CLASS_NAME, resolveOptions => {
+ .tap(CLASS_NAME, (resolveOptions) => {
resolveOptions = cleverMerge(options.resolve, resolveOptions);
resolveOptions.fileSystem =
/** @type {InputFileSystem} */
@@ -877,7 +877,7 @@ class WebpackOptionsApply extends OptionsApply {
});
compiler.resolverFactory.hooks.resolveOptions
.for("loader")
- .tap(CLASS_NAME, resolveOptions => {
+ .tap(CLASS_NAME, (resolveOptions) => {
resolveOptions = cleverMerge(options.resolveLoader, resolveOptions);
resolveOptions.fileSystem =
/** @type {InputFileSystem} */
diff --git a/lib/asset/AssetGenerator.js b/lib/asset/AssetGenerator.js
index 90cb71b23ae..f1e1c025045 100644
--- a/lib/asset/AssetGenerator.js
+++ b/lib/asset/AssetGenerator.js
@@ -152,7 +152,7 @@ const encodeDataUri = (encoding, source) => {
(encodedContent)
).replace(
/[!'()*]/g,
- character =>
+ (character) =>
`%${/** @type {number} */ (character.codePointAt(0)).toString(16)}`
);
break;
diff --git a/lib/asset/AssetModulesPlugin.js b/lib/asset/AssetModulesPlugin.js
index 7ee4370e0f5..7b317cf5523 100644
--- a/lib/asset/AssetModulesPlugin.js
+++ b/lib/asset/AssetModulesPlugin.js
@@ -31,7 +31,7 @@ const memoize = require("../util/memoize");
* @param {string} name name of definitions
* @returns {Schema} definition
*/
-const getSchema = name => {
+const getSchema = (name) => {
const { definitions } = require("../../schemas/WebpackOptions.json");
return {
@@ -93,7 +93,7 @@ class AssetModulesPlugin {
(compilation, { normalModuleFactory }) => {
normalModuleFactory.hooks.createParser
.for(ASSET_MODULE_TYPE)
- .tap(PLUGIN_NAME, parserOptions => {
+ .tap(PLUGIN_NAME, (parserOptions) => {
validateParserOptions(parserOptions);
parserOptions = cleverMerge(
/** @type {AssetParserOptions} */
@@ -115,21 +115,21 @@ class AssetModulesPlugin {
});
normalModuleFactory.hooks.createParser
.for(ASSET_MODULE_TYPE_INLINE)
- .tap(PLUGIN_NAME, _parserOptions => {
+ .tap(PLUGIN_NAME, (_parserOptions) => {
const AssetParser = getAssetParser();
return new AssetParser(true);
});
normalModuleFactory.hooks.createParser
.for(ASSET_MODULE_TYPE_RESOURCE)
- .tap(PLUGIN_NAME, _parserOptions => {
+ .tap(PLUGIN_NAME, (_parserOptions) => {
const AssetParser = getAssetParser();
return new AssetParser(false);
});
normalModuleFactory.hooks.createParser
.for(ASSET_MODULE_TYPE_SOURCE)
- .tap(PLUGIN_NAME, _parserOptions => {
+ .tap(PLUGIN_NAME, (_parserOptions) => {
const AssetSourceParser = getAssetSourceParser();
return new AssetSourceParser();
@@ -142,7 +142,7 @@ class AssetModulesPlugin {
]) {
normalModuleFactory.hooks.createGenerator
.for(type)
- .tap(PLUGIN_NAME, generatorOptions => {
+ .tap(PLUGIN_NAME, (generatorOptions) => {
validateGeneratorOptions[type](generatorOptions);
let dataUrl;
diff --git a/lib/async-modules/AsyncModuleHelpers.js b/lib/async-modules/AsyncModuleHelpers.js
index e0c69bb60eb..df45deca503 100644
--- a/lib/async-modules/AsyncModuleHelpers.js
+++ b/lib/async-modules/AsyncModuleHelpers.js
@@ -32,7 +32,7 @@ const getOutgoingAsyncModules = (moduleGraph, module) => {
for (const [module, connections] of outgoingConnectionMap) {
if (
connections.some(
- c =>
+ (c) =>
c.dependency instanceof HarmonyImportDependency &&
c.isTargetActive(undefined)
) &&
diff --git a/lib/async-modules/AwaitDependenciesInitFragment.js b/lib/async-modules/AwaitDependenciesInitFragment.js
index 178834b06e7..0928d59271e 100644
--- a/lib/async-modules/AwaitDependenciesInitFragment.js
+++ b/lib/async-modules/AwaitDependenciesInitFragment.js
@@ -17,16 +17,16 @@ const Template = require("../Template");
*/
class AwaitDependenciesInitFragment extends InitFragment {
/**
- * @param {Set} promises the promises that should be awaited
+ * @param {Map} dependencies maps an import var to an async module that needs to be awaited
*/
- constructor(promises) {
+ constructor(dependencies) {
super(
undefined,
InitFragment.STAGE_ASYNC_DEPENDENCIES,
0,
"await-dependencies"
);
- this.promises = promises;
+ this.dependencies = dependencies;
}
/**
@@ -34,38 +34,50 @@ class AwaitDependenciesInitFragment extends InitFragment {
* @returns {AwaitDependenciesInitFragment} AwaitDependenciesInitFragment
*/
merge(other) {
- const promises = new Set(other.promises);
- for (const p of this.promises) {
- promises.add(p);
+ const dependencies = new Map(other.dependencies);
+ for (const [key, value] of this.dependencies) {
+ dependencies.set(key, value);
}
- return new AwaitDependenciesInitFragment(promises);
+ return new AwaitDependenciesInitFragment(dependencies);
}
/**
* @param {GenerateContext} context context
* @returns {string | Source | undefined} the source code that will be included as initialization code
*/
- getContent({ runtimeRequirements }) {
+ getContent({ runtimeRequirements, runtimeTemplate }) {
runtimeRequirements.add(RuntimeGlobals.module);
- const promises = this.promises;
- if (promises.size === 0) {
+ if (this.dependencies.size === 0) {
return "";
}
- if (promises.size === 1) {
- const [p] = promises;
- return Template.asString([
- `var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([${p}]);`,
- `${p} = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0];`,
- ""
- ]);
+
+ const importVars = [...this.dependencies.keys()];
+ const asyncModuleValues = [...this.dependencies.values()].join(", ");
+
+ const templateInput = [
+ `var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([${asyncModuleValues}]);`
+ ];
+
+ if (
+ this.dependencies.size === 1 ||
+ !runtimeTemplate.supportsDestructuring()
+ ) {
+ for (const [index, importVar] of importVars.entries()) {
+ templateInput.push(
+ `${importVar} = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[${index}];`
+ );
+ }
+ } else {
+ const importVarsStr = importVars.join(", ");
+
+ templateInput.push(
+ `([${importVarsStr}] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);`
+ );
}
- const sepPromises = [...promises].join(", ");
- // TODO check if destructuring is supported
- return Template.asString([
- `var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([${sepPromises}]);`,
- `([${sepPromises}] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);`,
- ""
- ]);
+
+ templateInput.push("");
+
+ return Template.asString(templateInput);
}
}
diff --git a/lib/async-modules/InferAsyncModulesPlugin.js b/lib/async-modules/InferAsyncModulesPlugin.js
index f585aac5c98..3ced0bcc63d 100644
--- a/lib/async-modules/InferAsyncModulesPlugin.js
+++ b/lib/async-modules/InferAsyncModulesPlugin.js
@@ -19,9 +19,9 @@ class InferAsyncModulesPlugin {
* @returns {void}
*/
apply(compiler) {
- compiler.hooks.compilation.tap(PLUGIN_NAME, compilation => {
+ compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
const { moduleGraph } = compilation;
- compilation.hooks.finishModules.tap(PLUGIN_NAME, modules => {
+ compilation.hooks.finishModules.tap(PLUGIN_NAME, (modules) => {
/** @type {Set} */
const queue = new Set();
for (const module of modules) {
@@ -37,7 +37,7 @@ class InferAsyncModulesPlugin {
] of moduleGraph.getIncomingConnectionsByOriginModule(module)) {
if (
connections.some(
- c =>
+ (c) =>
c.dependency instanceof HarmonyImportDependency &&
c.isTargetActive(undefined)
)
diff --git a/lib/buildChunkGraph.js b/lib/buildChunkGraph.js
index 9cd54164b96..117e98ed394 100644
--- a/lib/buildChunkGraph.js
+++ b/lib/buildChunkGraph.js
@@ -269,7 +269,7 @@ const visitModules = (
* @param {Module} module The module to look up
* @returns {number} The ordinal of the module in masks
*/
- const getModuleOrdinal = module => {
+ const getModuleOrdinal = (module) => {
let ordinal = ordinalByModule.get(module);
if (ordinal === undefined) {
ordinal = ordinalByModule.size;
@@ -486,7 +486,7 @@ const visitModules = (
* @param {AsyncDependenciesBlock} b iterating over each Async DepBlock
* @returns {void}
*/
- const iteratorBlock = b => {
+ const iteratorBlock = (b) => {
// 1. We create a chunk group with single chunk in it for this Block
// but only once (blockChunkGroups map)
/** @type {ChunkGroupInfo | undefined} */
@@ -673,7 +673,7 @@ const visitModules = (
* @param {DependenciesBlock} block the block
* @returns {void}
*/
- const processBlock = block => {
+ const processBlock = (block) => {
statProcessedBlocks++;
// get prepared block info
const blockModules = getBlockModules(block, chunkGroupInfo.runtime);
@@ -765,7 +765,7 @@ const visitModules = (
* @param {DependenciesBlock} block the block
* @returns {void}
*/
- const processEntryBlock = block => {
+ const processEntryBlock = (block) => {
statProcessedBlocks++;
// get prepared block info
const blockModules = getBlockModules(block, chunkGroupInfo.runtime);
@@ -892,7 +892,7 @@ const visitModules = (
* @param {ChunkGroupInfo} chunkGroupInfo The info object for the chunk group
* @returns {bigint} The mask of available modules after the chunk group
*/
- const calculateResultingAvailableModules = chunkGroupInfo => {
+ const calculateResultingAvailableModules = (chunkGroupInfo) => {
if (chunkGroupInfo.resultingAvailableModules !== undefined) {
return chunkGroupInfo.resultingAvailableModules;
}
diff --git a/lib/cache/AddBuildDependenciesPlugin.js b/lib/cache/AddBuildDependenciesPlugin.js
index 7d8b1d0775b..7d271e26a5d 100644
--- a/lib/cache/AddBuildDependenciesPlugin.js
+++ b/lib/cache/AddBuildDependenciesPlugin.js
@@ -23,7 +23,7 @@ class AddBuildDependenciesPlugin {
* @returns {void}
*/
apply(compiler) {
- compiler.hooks.compilation.tap(PLUGIN_NAME, compilation => {
+ compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
compilation.buildDependencies.addAll(this.buildDependencies);
});
}
diff --git a/lib/cache/IdleFileCachePlugin.js b/lib/cache/IdleFileCachePlugin.js
index 90708076574..78ef83b9964 100644
--- a/lib/cache/IdleFileCachePlugin.js
+++ b/lib/cache/IdleFileCachePlugin.js
@@ -68,7 +68,7 @@ class IdleFileCachePlugin {
{ name: PLUGIN_NAME, stage: Cache.STAGE_DISK },
(identifier, etag, gotHandlers) => {
const restore = () =>
- strategy.restore(identifier, etag).then(cacheEntry => {
+ strategy.restore(identifier, etag).then((cacheEntry) => {
if (cacheEntry === undefined) {
gotHandlers.push((result, callback) => {
if (result !== undefined) {
@@ -93,7 +93,7 @@ class IdleFileCachePlugin {
compiler.cache.hooks.storeBuildDependencies.tap(
{ name: PLUGIN_NAME, stage: Cache.STAGE_DISK },
- dependencies => {
+ (dependencies) => {
pendingIdleTasks.set(BUILD_DEPENDENCIES_KEY, () =>
Promise.resolve().then(() =>
strategy.storeBuildDependencies(dependencies)
@@ -113,7 +113,7 @@ class IdleFileCachePlugin {
const reportProgress = ProgressPlugin.getReporter(compiler);
const jobs = [...pendingIdleTasks.values()];
if (reportProgress) reportProgress(0, "process pending cache items");
- const promises = jobs.map(fn => fn());
+ const promises = jobs.map((fn) => fn());
pendingIdleTasks.clear();
promises.push(currentIdlePromise);
const promise = Promise.all(promises);
@@ -168,7 +168,7 @@ class IdleFileCachePlugin {
timeSpendInStore = 0;
timeSpendInBuild = 0;
})
- .catch(err => {
+ .catch((err) => {
const logger = compiler.getInfrastructureLogger(PLUGIN_NAME);
logger.warn(`Background tasks during idle failed: ${err.message}`);
logger.debug(err.stack);
@@ -229,7 +229,7 @@ class IdleFileCachePlugin {
isIdle = false;
}
);
- compiler.hooks.done.tap(PLUGIN_NAME, stats => {
+ compiler.hooks.done.tap(PLUGIN_NAME, (stats) => {
// 10% build overhead is ignored, as it's not cacheable
timeSpendInBuild *= 0.9;
timeSpendInBuild +=
diff --git a/lib/cache/PackFileCacheStrategy.js b/lib/cache/PackFileCacheStrategy.js
index 29bcf18e55a..0c8ab23e926 100644
--- a/lib/cache/PackFileCacheStrategy.js
+++ b/lib/cache/PackFileCacheStrategy.js
@@ -330,7 +330,7 @@ class Pack {
`${itemsCount} fresh items in cache put into pack ${
packs.length > 1
? packs
- .map(pack => `${pack.loc} (${pack.items.size} items)`)
+ .map((pack) => `${pack.loc} (${pack.items.size} items)`)
.join(", ")
: packs[0].loc
}`
@@ -407,7 +407,7 @@ class Pack {
for (const identifier of content.used) {
mergedUsedItems.add(identifier);
}
- addToMergedMap.push(async map => {
+ addToMergedMap.push(async (map) => {
// unpack existing content
// after that values are accessible in .content
await content.unpack(
@@ -433,7 +433,7 @@ class Pack {
memoize(async () => {
/** @type {Content} */
const map = new Map();
- await Promise.all(addToMergedMap.map(fn => fn(map)));
+ await Promise.all(addToMergedMap.map((fn) => fn(map)));
return new PackContentItems(map);
})
);
@@ -603,7 +603,7 @@ class Pack {
const content = this.content[i];
if (content !== undefined) {
write(content.items);
- content.writeLazy(lazy =>
+ content.writeLazy((lazy) =>
/** @type {NonNullable} */
(writeSeparate)(lazy, { name: `${i}` })
);
@@ -627,7 +627,7 @@ class Pack {
item = read();
}
this.itemInfo.clear();
- const infoItems = items.map(identifier => {
+ const infoItems = items.map((identifier) => {
const info = new PackItemInfo(identifier, undefined, undefined);
this.itemInfo.set(identifier, info);
return info;
@@ -875,7 +875,7 @@ class PackContent {
}
const value = /** @type {LazyFunction} */ (this.lazy)();
if ("then" in value) {
- return value.then(data => {
+ return value.then((data) => {
const map = data.map;
if (timeMessage) {
logger.timeEnd(timeMessage);
@@ -927,7 +927,7 @@ class PackContent {
/** @type {PackContentItems | Promise} */
(this.lazy());
if ("then" in value) {
- return value.then(data => {
+ return value.then((data) => {
if (timeMessage) {
logger.timeEnd(timeMessage);
}
@@ -1022,7 +1022,7 @@ class PackContent {
if ("then" in value) {
// Move to state B1
this.lazy = write(() =>
- value.then(data => {
+ value.then((data) => {
if (timeMessage) {
logger.timeEnd(timeMessage);
}
@@ -1060,7 +1060,7 @@ class PackContent {
* @param {Buffer} buf buffer
* @returns {Buffer} buffer that can be collected
*/
-const allowCollectingMemory = buf => {
+const allowCollectingMemory = (buf) => {
const wasted = buf.buffer.byteLength - buf.byteLength;
if (wasted > 8192 && (wasted > 1048576 || wasted > buf.byteLength)) {
return Buffer.from(buf);
@@ -1178,7 +1178,7 @@ class PackFileCacheStrategy {
? allowCollectingMemory
: undefined
})
- .catch(err => {
+ .catch((err) => {
if (err.code !== "ENOENT") {
logger.warn(
`Restoring pack failed from ${cacheLocation}${this._extension}: ${err}`
@@ -1191,7 +1191,7 @@ class PackFileCacheStrategy {
}
return undefined;
})
- .then(packContainer => {
+ .then((packContainer) => {
logger.timeEnd("restore cache container");
if (!packContainer) return;
if (!(packContainer instanceof PackContainer)) {
@@ -1277,7 +1277,7 @@ class PackFileCacheStrategy {
);
})
])
- .catch(err => {
+ .catch((err) => {
logger.timeEnd("check build dependencies");
throw err;
})
@@ -1292,7 +1292,7 @@ class PackFileCacheStrategy {
return undefined;
});
})
- .then(pack => {
+ .then((pack) => {
if (pack) {
pack.maxAge = this.maxAge;
this.buildSnapshot = buildSnapshot;
@@ -1307,7 +1307,7 @@ class PackFileCacheStrategy {
}
return new Pack(logger, this.maxAge);
})
- .catch(err => {
+ .catch((err) => {
this.logger.warn(
`Restoring pack from ${cacheLocation}${this._extension} failed: ${err}`
);
@@ -1325,7 +1325,7 @@ class PackFileCacheStrategy {
store(identifier, etag, data) {
if (this.readonly) return Promise.resolve();
- return this._getPack().then(pack => {
+ return this._getPack().then((pack) => {
pack.set(identifier, etag === null ? null : etag.toString(), data);
});
}
@@ -1337,10 +1337,10 @@ class PackFileCacheStrategy {
*/
restore(identifier, etag) {
return this._getPack()
- .then(pack =>
+ .then((pack) =>
pack.get(identifier, etag === null ? null : etag.toString())
)
- .catch(err => {
+ .catch((err) => {
if (err && err.code !== "ENOENT") {
this.logger.warn(
`Restoring failed for ${identifier} from pack: ${err}`
@@ -1363,7 +1363,7 @@ class PackFileCacheStrategy {
if (packPromise === undefined) return Promise.resolve();
const reportProgress = ProgressPlugin.getReporter(this.compiler);
return (this.storePromise = packPromise
- .then(pack => {
+ .then((pack) => {
pack.stopCapturingRequests();
if (!pack.invalid) return;
this.packPromise = undefined;
@@ -1526,14 +1526,14 @@ class PackFileCacheStrategy {
Math.round(stats.size / 1024 / 1024)
);
})
- .catch(err => {
+ .catch((err) => {
this.logger.timeEnd("store pack");
this.logger.warn(`Caching failed for pack: ${err}`);
this.logger.debug(err.stack);
});
});
})
- .catch(err => {
+ .catch((err) => {
this.logger.warn(`Caching failed for pack: ${err}`);
this.logger.debug(err.stack);
}));
diff --git a/lib/cache/ResolverCachePlugin.js b/lib/cache/ResolverCachePlugin.js
index 8e918546a02..e28a8896c4a 100644
--- a/lib/cache/ResolverCachePlugin.js
+++ b/lib/cache/ResolverCachePlugin.js
@@ -115,7 +115,7 @@ class ResolverCachePlugin {
let cachedResolves = 0;
let cacheInvalidResolves = 0;
let concurrentResolves = 0;
- compiler.hooks.thisCompilation.tap(PLUGIN_NAME, compilation => {
+ compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {
snapshotOptions = compilation.options.snapshot.resolve;
fileSystemInfo = compilation.fileSystemInfo;
compilation.hooks.finishModules.tap(PLUGIN_NAME, () => {
@@ -176,14 +176,14 @@ class ResolverCachePlugin {
if (typeof newResolveContext.yield === "function") {
yieldResult = [];
withYield = true;
- newResolveContext.yield = obj =>
+ newResolveContext.yield = (obj) =>
/** @type {ResolveRequest[]} */
(yieldResult).push(obj);
}
/**
* @param {"fileDependencies" | "contextDependencies" | "missingDependencies"} key key
*/
- const propagate = key => {
+ const propagate = (key) => {
if (resolveContext[key]) {
addAllToSet(
/** @type {Set} */ (resolveContext[key]),
@@ -239,7 +239,7 @@ class ResolverCachePlugin {
(resolveResult),
snapshot
),
- storeErr => {
+ (storeErr) => {
if (storeErr) return callback(storeErr);
if (resolveResult) {
return callback(
diff --git a/lib/cli.js b/lib/cli.js
index 642bde742c3..1d38af32bc8 100644
--- a/lib/cli.js
+++ b/lib/cli.js
@@ -6,6 +6,7 @@
"use strict";
const path = require("path");
+const tty = require("tty");
const webpackSchema = require("../schemas/WebpackOptions.json");
/** @typedef {import("json-schema").JSONSchema4} JSONSchema4 */
@@ -82,7 +83,7 @@ const getArguments = (schema = webpackSchema) => {
* @param {string} input input
* @returns {string} result
*/
- const pathToArgumentName = input =>
+ const pathToArgumentName = (input) =>
input
.replace(/\./g, "-")
.replace(/\[\]/g, "")
@@ -97,7 +98,7 @@ const getArguments = (schema = webpackSchema) => {
* @param {string} path path
* @returns {Schema} schema part
*/
- const getSchemaPart = path => {
+ const getSchemaPart = (path) => {
const newPath = path.split("/");
let schemaPart = schema;
@@ -119,7 +120,7 @@ const getArguments = (schema = webpackSchema) => {
* @param {PathItem[]} path path in the schema
* @returns {string | undefined} description
*/
- const getDescription = path => {
+ const getDescription = (path) => {
for (const { schema } of path) {
if (schema.cli) {
if (schema.cli.helper) continue;
@@ -133,7 +134,7 @@ const getArguments = (schema = webpackSchema) => {
* @param {PathItem[]} path path in the schema
* @returns {string | undefined} negative description
*/
- const getNegatedDescription = path => {
+ const getNegatedDescription = (path) => {
for (const { schema } of path) {
if (schema.cli) {
if (schema.cli.helper) continue;
@@ -146,7 +147,7 @@ const getArguments = (schema = webpackSchema) => {
* @param {PathItem[]} path path in the schema
* @returns {string | undefined} reset description
*/
- const getResetDescription = path => {
+ const getResetDescription = (path) => {
for (const { schema } of path) {
if (schema.cli) {
if (schema.cli.helper) continue;
@@ -159,7 +160,7 @@ const getArguments = (schema = webpackSchema) => {
* @param {Schema} schemaPart schema
* @returns {Pick | undefined} partial argument config
*/
- const schemaToArgumentConfig = schemaPart => {
+ const schemaToArgumentConfig = (schemaPart) => {
if (schemaPart.enum) {
return {
type: "enum",
@@ -192,7 +193,7 @@ const getArguments = (schema = webpackSchema) => {
* @param {PathItem[]} path path in the schema
* @returns {void}
*/
- const addResetFlag = path => {
+ const addResetFlag = (path) => {
const schemaPath = path[0].path;
const name = pathToArgumentName(`${schemaPath}.reset`);
const description =
@@ -253,7 +254,7 @@ const getArguments = (schema = webpackSchema) => {
if (
flags[name].configs.some(
- item => JSON.stringify(item) === JSON.stringify(argConfig)
+ (item) => JSON.stringify(item) === JSON.stringify(argConfig)
)
) {
return 0;
@@ -261,7 +262,7 @@ const getArguments = (schema = webpackSchema) => {
if (
flags[name].configs.some(
- item => item.type === argConfig.type && item.multiple !== multiple
+ (item) => item.type === argConfig.type && item.multiple !== multiple
)
) {
if (multiple) {
@@ -411,8 +412,8 @@ const getArguments = (schema = webpackSchema) => {
/** @type {NonNullable} */
(argConfig.values);
- if (values.every(v => typeof v === "boolean")) type = "boolean";
- if (values.every(v => typeof v === "number")) type = "number";
+ if (values.every((v) => typeof v === "boolean")) type = "boolean";
+ if (values.every((v) => typeof v === "number")) type = "number";
break;
}
}
@@ -420,7 +421,7 @@ const getArguments = (schema = webpackSchema) => {
return t === type ? t : "string";
}, /** @type {SimpleType | undefined} */ (undefined))
);
- argument.multiple = argument.configs.some(c => c.multiple);
+ argument.multiple = argument.configs.some((c) => c.multiple);
}
return flags;
@@ -580,7 +581,7 @@ const processArgumentConfig = (argConfig, config, value, index) => {
* @param {ArgumentConfig} argConfig processing instructions
* @returns {string | undefined} expected message
*/
-const getExpectedValue = argConfig => {
+const getExpectedValue = (argConfig) => {
switch (argConfig.type) {
case "boolean":
return "true | false";
@@ -590,7 +591,7 @@ const getExpectedValue = argConfig => {
return /** @type {NonNullable} */ (
argConfig.values
)
- .map(v => `${v}`)
+ .map((v) => `${v}`)
.join(" | ");
case "reset":
return "true (will reset the previous value to an empty array)";
@@ -712,5 +713,186 @@ const processArguments = (args, config, values) => {
return problems;
};
+/**
+ * @returns {boolean} true when colors supported, otherwise false
+ */
+const isColorSupported = () => {
+ const { env = {}, argv = [], platform = "" } = process;
+
+ const isDisabled = "NO_COLOR" in env || argv.includes("--no-color");
+ const isForced = "FORCE_COLOR" in env || argv.includes("--color");
+ const isWindows = platform === "win32";
+ const isDumbTerminal = env.TERM === "dumb";
+
+ const isCompatibleTerminal = tty.isatty(1) && env.TERM && !isDumbTerminal;
+
+ const isCI =
+ "CI" in env &&
+ ("GITHUB_ACTIONS" in env || "GITLAB_CI" in env || "CIRCLECI" in env);
+
+ return (
+ !isDisabled &&
+ (isForced || (isWindows && !isDumbTerminal) || isCompatibleTerminal || isCI)
+ );
+};
+
+/**
+ * @param {number} index index
+ * @param {string} string string
+ * @param {string} close close
+ * @param {string=} replace replace
+ * @param {string=} head head
+ * @param {string=} tail tail
+ * @param {number=} next next
+ * @returns {string} result
+ */
+const replaceClose = (
+ index,
+ string,
+ close,
+ replace,
+ head = string.slice(0, Math.max(0, index)) + replace,
+ tail = string.slice(Math.max(0, index + close.length)),
+ next = tail.indexOf(close)
+) => head + (next < 0 ? tail : replaceClose(next, tail, close, replace));
+
+/**
+ * @param {number} index index to replace
+ * @param {string} string string
+ * @param {string} open open string
+ * @param {string} close close string
+ * @param {string=} replace extra replace
+ * @returns {string} result
+ */
+const clearBleed = (index, string, open, close, replace) =>
+ index < 0
+ ? open + string + close
+ : open + replaceClose(index, string, close, replace) + close;
+
+/** @typedef {(value: EXPECTED_ANY) => string} PrintFunction */
+
+/**
+ * @param {string} open open string
+ * @param {string} close close string
+ * @param {string=} replace extra replace
+ * @param {number=} at at
+ * @returns {PrintFunction} function to create color
+ */
+const filterEmpty =
+ (open, close, replace = open, at = open.length + 1) =>
+ (string) =>
+ string || !(string === "" || string === undefined)
+ ? clearBleed(`${string}`.indexOf(close, at), string, open, close, replace)
+ : "";
+
+/**
+ * @param {number} open open code
+ * @param {number} close close code
+ * @param {string=} replace extra replace
+ * @returns {PrintFunction} result
+ */
+const init = (open, close, replace) =>
+ filterEmpty(`\u001B[${open}m`, `\u001B[${close}m`, replace);
+
+/**
+ * @typedef {{
+ * reset: PrintFunction
+ * bold: PrintFunction
+ * dim: PrintFunction
+ * italic: PrintFunction
+ * underline: PrintFunction
+ * inverse: PrintFunction
+ * hidden: PrintFunction
+ * strikethrough: PrintFunction
+ * black: PrintFunction
+ * red: PrintFunction
+ * green: PrintFunction
+ * yellow: PrintFunction
+ * blue: PrintFunction
+ * magenta: PrintFunction
+ * cyan: PrintFunction
+ * white: PrintFunction
+ * gray: PrintFunction
+ * bgBlack: PrintFunction
+ * bgRed: PrintFunction
+ * bgGreen: PrintFunction
+ * bgYellow: PrintFunction
+ * bgBlue: PrintFunction
+ * bgMagenta: PrintFunction
+ * bgCyan: PrintFunction
+ * bgWhite: PrintFunction
+ * blackBright: PrintFunction
+ * redBright: PrintFunction
+ * greenBright: PrintFunction
+ * yellowBright: PrintFunction
+ * blueBright: PrintFunction
+ * magentaBright: PrintFunction
+ * cyanBright: PrintFunction
+ * whiteBright: PrintFunction
+ * bgBlackBright: PrintFunction
+ * bgRedBright: PrintFunction
+ * bgGreenBright: PrintFunction
+ * bgYellowBright: PrintFunction
+ * bgBlueBright: PrintFunction
+ * bgMagentaBright: PrintFunction
+ * bgCyanBright: PrintFunction
+ * bgWhiteBright: PrintFunction
+ }} Colors */
+
+/**
+ * @typedef {object} ColorsOptions
+ * @property {boolean=} useColor force use colors
+ */
+
+/**
+ * @param {ColorsOptions=} options options
+ * @returns {Colors} colors
+ */
+const createColors = ({ useColor = isColorSupported() } = {}) => ({
+ reset: useColor ? init(0, 0) : String,
+ bold: useColor ? init(1, 22, "\u001B[22m\u001B[1m") : String,
+ dim: useColor ? init(2, 22, "\u001B[22m\u001B[2m") : String,
+ italic: useColor ? init(3, 23) : String,
+ underline: useColor ? init(4, 24) : String,
+ inverse: useColor ? init(7, 27) : String,
+ hidden: useColor ? init(8, 28) : String,
+ strikethrough: useColor ? init(9, 29) : String,
+ black: useColor ? init(30, 39) : String,
+ red: useColor ? init(31, 39) : String,
+ green: useColor ? init(32, 39) : String,
+ yellow: useColor ? init(33, 39) : String,
+ blue: useColor ? init(34, 39) : String,
+ magenta: useColor ? init(35, 39) : String,
+ cyan: useColor ? init(36, 39) : String,
+ white: useColor ? init(37, 39) : String,
+ gray: useColor ? init(90, 39) : String,
+ bgBlack: useColor ? init(40, 49) : String,
+ bgRed: useColor ? init(41, 49) : String,
+ bgGreen: useColor ? init(42, 49) : String,
+ bgYellow: useColor ? init(43, 49) : String,
+ bgBlue: useColor ? init(44, 49) : String,
+ bgMagenta: useColor ? init(45, 49) : String,
+ bgCyan: useColor ? init(46, 49) : String,
+ bgWhite: useColor ? init(47, 49) : String,
+ blackBright: useColor ? init(90, 39) : String,
+ redBright: useColor ? init(91, 39) : String,
+ greenBright: useColor ? init(92, 39) : String,
+ yellowBright: useColor ? init(93, 39) : String,
+ blueBright: useColor ? init(94, 39) : String,
+ magentaBright: useColor ? init(95, 39) : String,
+ cyanBright: useColor ? init(96, 39) : String,
+ whiteBright: useColor ? init(97, 39) : String,
+ bgBlackBright: useColor ? init(100, 49) : String,
+ bgRedBright: useColor ? init(101, 49) : String,
+ bgGreenBright: useColor ? init(102, 49) : String,
+ bgYellowBright: useColor ? init(103, 49) : String,
+ bgBlueBright: useColor ? init(104, 49) : String,
+ bgMagentaBright: useColor ? init(105, 49) : String,
+ bgCyanBright: useColor ? init(106, 49) : String,
+ bgWhiteBright: useColor ? init(107, 49) : String
+});
+
+module.exports.createColors = createColors;
module.exports.getArguments = getArguments;
+module.exports.isColorSupported = isColorSupported;
module.exports.processArguments = processArguments;
diff --git a/lib/config/browserslistTargetHandler.js b/lib/config/browserslistTargetHandler.js
index 09bf23dd336..196cfa143fe 100644
--- a/lib/config/browserslistTargetHandler.js
+++ b/lib/config/browserslistTargetHandler.js
@@ -74,14 +74,14 @@ const load = (input, context) => {
* @param {string[]} browsers supported browsers list
* @returns {EcmaTargetProperties & PlatformTargetProperties & ApiTargetProperties} target properties
*/
-const resolve = browsers => {
+const resolve = (browsers) => {
/**
* Checks all against a version number
* @param {Record} versions first supported version
* @returns {boolean} true if supports
*/
- const rawChecker = versions =>
- browsers.every(v => {
+ const rawChecker = (versions) =>
+ browsers.every((v) => {
const [name, parsedVersion] = v.split(" ");
if (!name) return false;
const requiredVersion = versions[name];
@@ -100,8 +100,8 @@ const resolve = browsers => {
? Number(parserMinor) >= requiredVersion[1]
: Number(parsedMajor) > requiredVersion[0];
});
- const anyNode = browsers.some(b => b.startsWith("node "));
- const anyBrowser = browsers.some(b => /^(?!node)/.test(b));
+ const anyNode = browsers.some((b) => b.startsWith("node "));
+ const anyBrowser = browsers.some((b) => /^(?!node)/.test(b));
const browserProperty = !anyBrowser ? false : anyNode ? null : true;
const nodeProperty = !anyNode ? false : anyBrowser ? null : true;
// Internet Explorer Mobile, Blackberry browser and Opera Mini are very old browsers, they do not support new features
@@ -349,7 +349,7 @@ const resolve = browsers => {
nodeBuiltins: nodeProperty,
nodePrefixForCoreModules:
nodeProperty &&
- !browsers.some(b => b.startsWith("node 15")) &&
+ !browsers.some((b) => b.startsWith("node 15")) &&
rawChecker({
node: [14, 18]
}),
diff --git a/lib/config/defaults.js b/lib/config/defaults.js
index 3f4c4618a74..613968ab84f 100644
--- a/lib/config/defaults.js
+++ b/lib/config/defaults.js
@@ -159,7 +159,7 @@ const A = (obj, prop, factory) => {
* @param {WebpackOptionsNormalized} options options to be modified
* @returns {void}
*/
-const applyWebpackOptionsBaseDefaults = options => {
+const applyWebpackOptionsBaseDefaults = (options) => {
F(options, "context", () => process.cwd());
applyInfrastructureLoggingDefaults(options.infrastructureLogging);
};
@@ -242,7 +242,7 @@ const applyWebpackOptionsDefaults = (options, compilerIndex) => {
target === undefined ||
(typeof target === "string" && target.startsWith("browserslist")) ||
(Array.isArray(target) &&
- target.some(target => target.startsWith("browserslist"))),
+ target.some((target) => target.startsWith("browserslist"))),
outputModule:
/** @type {NonNullable} */
(options.experiments.outputModule),
@@ -265,6 +265,9 @@ const applyWebpackOptionsDefaults = (options, compilerIndex) => {
css:
/** @type {NonNullable} */
(options.experiments.css),
+ deferImport:
+ /** @type {NonNullable} */
+ (options.experiments.deferImport),
futureDefaults,
isNode: targetProperties && targetProperties.node === true,
uniqueName: /** @type {string} */ (options.output.uniqueName),
@@ -384,6 +387,7 @@ const applyExperimentsDefaults = (
D(experiments, "lazyCompilation", undefined);
D(experiments, "buildHttp", undefined);
D(experiments, "cacheUnaffected", experiments.futureDefaults);
+ D(experiments, "deferImport", false);
F(experiments, "css", () => (experiments.futureDefaults ? true : undefined));
// TODO webpack 6: remove this. topLevelAwait should be enabled by default
@@ -561,12 +565,13 @@ const applySnapshotDefaults = (snapshot, { production, futureDefaults }) => {
* @param {JavascriptParserOptions} parserOptions parser options
* @param {object} options options
* @param {boolean} options.futureDefaults is future defaults enabled
+ * @param {boolean} options.deferImport is defer import enabled
* @param {boolean} options.isNode is node target platform
* @returns {void}
*/
const applyJavascriptParserOptionsDefaults = (
parserOptions,
- { futureDefaults, isNode }
+ { futureDefaults, deferImport, isNode }
) => {
D(parserOptions, "unknownContextRequest", ".");
D(parserOptions, "unknownContextRegExp", false);
@@ -587,6 +592,7 @@ const applyJavascriptParserOptionsDefaults = (
D(parserOptions, "dynamicImportFetchPriority", false);
D(parserOptions, "createRequire", isNode);
D(parserOptions, "dynamicUrl", true);
+ D(parserOptions, "deferImport", deferImport);
if (futureDefaults) D(parserOptions, "exportsPresence", "error");
};
@@ -594,7 +600,7 @@ const applyJavascriptParserOptionsDefaults = (
* @param {JsonGeneratorOptions} generatorOptions generator options
* @returns {void}
*/
-const applyJsonGeneratorOptionsDefaults = generatorOptions => {
+const applyJsonGeneratorOptionsDefaults = (generatorOptions) => {
D(generatorOptions, "JSONParse", true);
};
@@ -626,6 +632,7 @@ const applyCssGeneratorOptionsDefaults = (
* @param {boolean} options.futureDefaults is future defaults enabled
* @param {string} options.uniqueName the unique name
* @param {boolean} options.isNode is node target platform
+ * @param {boolean} options.deferImport is defer import enabled
* @param {TargetProperties | false} options.targetProperties target properties
* @param {Mode | undefined} options.mode mode
* @returns {void}
@@ -641,7 +648,8 @@ const applyModuleDefaults = (
isNode,
uniqueName,
targetProperties,
- mode
+ mode,
+ deferImport
}
) => {
if (cache) {
@@ -652,7 +660,7 @@ const applyModuleDefaults = (
* @param {Module} module module
* @returns {boolean} true, if we want to cache the module
*/
- module => {
+ (module) => {
const name = module.nameForCondition();
if (!name) {
return false;
@@ -699,6 +707,7 @@ const applyModuleDefaults = (
(module.parser.javascript),
{
futureDefaults,
+ deferImport,
isNode
}
);
@@ -964,7 +973,7 @@ const applyOutputDefaults = (
* @param {Library=} library the library option
* @returns {string} a readable library name
*/
- const getLibraryName = library => {
+ const getLibraryName = (library) => {
const libraryName =
typeof library === "object" &&
library &&
@@ -1015,7 +1024,7 @@ const applyOutputDefaults = (
* @param {boolean | undefined} v value
* @returns {boolean} true, when v is truthy or undefined
*/
- const optimistic = v => v || v === undefined;
+ const optimistic = (v) => v || v === undefined;
/**
* @param {boolean | undefined} v value
* @param {boolean | undefined} c condition
@@ -1322,7 +1331,7 @@ const applyOutputDefaults = (
* @param {(entryDescription: EntryDescription) => void} fn iterator
* @returns {void}
*/
- const forEachEntry = fn => {
+ const forEachEntry = (fn) => {
for (const name of Object.keys(entry)) {
fn(/** @type {{[k: string] : EntryDescription}} */ (entry)[name]);
}
@@ -1333,7 +1342,7 @@ const applyOutputDefaults = (
if (output.library) {
enabledLibraryTypes.push(output.library.type);
}
- forEachEntry(desc => {
+ forEachEntry((desc) => {
if (desc.library) {
enabledLibraryTypes.push(desc.library.type);
}
@@ -1349,7 +1358,7 @@ const applyOutputDefaults = (
if (output.workerChunkLoading) {
enabledChunkLoadingTypes.add(output.workerChunkLoading);
}
- forEachEntry(desc => {
+ forEachEntry((desc) => {
if (desc.chunkLoading) {
enabledChunkLoadingTypes.add(desc.chunkLoading);
}
@@ -1365,7 +1374,7 @@ const applyOutputDefaults = (
if (output.workerWasmLoading) {
enabledWasmLoadingTypes.add(output.workerWasmLoading);
}
- forEachEntry(desc => {
+ forEachEntry((desc) => {
if (desc.wasmLoading) {
enabledWasmLoadingTypes.add(desc.wasmLoading);
}
@@ -1553,7 +1562,7 @@ const applyOptimizationDefaults = (
D(optimization, "minimize", production);
A(optimization, "minimizer", () => [
{
- apply: compiler => {
+ apply: (compiler) => {
// Lazy load the Terser plugin
const TerserPlugin = require("terser-webpack-plugin");
@@ -1735,7 +1744,7 @@ const getResolveLoaderDefaults = ({ cache }) => {
* @param {InfrastructureLogging} infrastructureLogging options
* @returns {void}
*/
-const applyInfrastructureLoggingDefaults = infrastructureLogging => {
+const applyInfrastructureLoggingDefaults = (infrastructureLogging) => {
F(infrastructureLogging, "stream", () => process.stderr);
const tty =
/** @type {NonNullable} */
diff --git a/lib/config/normalization.js b/lib/config/normalization.js
index 04a7a2d4ab2..fbd001c349b 100644
--- a/lib/config/normalization.js
+++ b/lib/config/normalization.js
@@ -57,7 +57,7 @@ const nestedConfig = (value, fn) =>
* @param {T|undefined} value value or not
* @returns {T} result value
*/
-const cloneObject = value => /** @type {T} */ ({ ...value });
+const cloneObject = (value) => /** @type {T} */ ({ ...value });
/**
* @template T
* @template R
@@ -124,13 +124,13 @@ const keyedNestedConfig = (value, fn, customKeys) => {
* @param {WebpackOptions} config input config
* @returns {WebpackOptionsNormalized} normalized options
*/
-const getNormalizedWebpackOptions = config => ({
+const getNormalizedWebpackOptions = (config) => ({
amd: config.amd,
bail: config.bail,
cache:
/** @type {NonNullable} */
(
- optionalNestedConfig(config.cache, cache => {
+ optionalNestedConfig(config.cache, (cache) => {
if (cache === false) return false;
if (cache === true) {
return {
@@ -173,7 +173,7 @@ const getNormalizedWebpackOptions = config => ({
),
context: config.context,
dependencies: config.dependencies,
- devServer: optionalNestedConfig(config.devServer, devServer => {
+ devServer: optionalNestedConfig(config.devServer, (devServer) => {
if (devServer === false) return false;
return { ...devServer };
}),
@@ -183,25 +183,25 @@ const getNormalizedWebpackOptions = config => ({
? { main: {} }
: typeof config.entry === "function"
? (
- fn => () =>
+ (fn) => () =>
Promise.resolve().then(fn).then(getNormalizedEntryStatic)
)(config.entry)
: getNormalizedEntryStatic(config.entry),
- experiments: nestedConfig(config.experiments, experiments => ({
+ experiments: nestedConfig(config.experiments, (experiments) => ({
...experiments,
- buildHttp: optionalNestedConfig(experiments.buildHttp, options =>
+ buildHttp: optionalNestedConfig(experiments.buildHttp, (options) =>
Array.isArray(options) ? { allowedUris: options } : options
),
lazyCompilation: optionalNestedConfig(
experiments.lazyCompilation,
- options => (options === true ? {} : options)
+ (options) => (options === true ? {} : options)
)
})),
externals: /** @type {NonNullable} */ (config.externals),
externalsPresets: cloneObject(config.externalsPresets),
externalsType: config.externalsType,
ignoreWarnings: config.ignoreWarnings
- ? config.ignoreWarnings.map(ignore => {
+ ? config.ignoreWarnings.map((ignore) => {
if (typeof ignore === "function") return ignore;
const i = ignore instanceof RegExp ? { message: ignore } : ignore;
return (warning, { requestShortener }) => {
@@ -236,11 +236,11 @@ const getNormalizedWebpackOptions = config => ({
module:
/** @type {ModuleOptionsNormalized} */
(
- nestedConfig(config.module, module => ({
+ nestedConfig(config.module, (module) => ({
noParse: module.noParse,
unsafeCache: module.unsafeCache,
parser: keyedNestedConfig(module.parser, cloneObject, {
- javascript: parserOptions => ({
+ javascript: (parserOptions) => ({
unknownContextRequest: module.unknownContextRequest,
unknownContextRegExp: module.unknownContextRegExp,
unknownContextRecursive: module.unknownContextRecursive,
@@ -259,26 +259,26 @@ const getNormalizedWebpackOptions = config => ({
})
}),
generator: cloneObject(module.generator),
- defaultRules: optionalNestedArray(module.defaultRules, r => [...r]),
- rules: nestedArray(module.rules, r => [...r])
+ defaultRules: optionalNestedArray(module.defaultRules, (r) => [...r]),
+ rules: nestedArray(module.rules, (r) => [...r])
}))
),
name: config.name,
node: nestedConfig(
config.node,
- node =>
+ (node) =>
node && {
...node
}
),
- optimization: nestedConfig(config.optimization, optimization => ({
+ optimization: nestedConfig(config.optimization, (optimization) => ({
...optimization,
runtimeChunk: getNormalizedOptimizationRuntimeChunk(
optimization.runtimeChunk
),
splitChunks: nestedConfig(
optimization.splitChunks,
- splitChunks =>
+ (splitChunks) =>
splitChunks && {
...splitChunks,
defaultSizeTypes: splitChunks.defaultSizeTypes
@@ -295,7 +295,7 @@ const getNormalizedWebpackOptions = config => ({
)
: optimization.emitOnErrors
})),
- output: nestedConfig(config.output, output => {
+ output: nestedConfig(config.output, (output) => {
const { library } = output;
const libraryAsName = /** @type {LibraryName} */ (library);
const libraryBase =
@@ -384,13 +384,16 @@ const getNormalizedWebpackOptions = config => ({
sourcePrefix: output.sourcePrefix,
strictModuleErrorHandling: output.strictModuleErrorHandling,
strictModuleExceptionHandling: output.strictModuleExceptionHandling,
- trustedTypes: optionalNestedConfig(output.trustedTypes, trustedTypes => {
- if (trustedTypes === true) return {};
- if (typeof trustedTypes === "string") {
- return { policyName: trustedTypes };
+ trustedTypes: optionalNestedConfig(
+ output.trustedTypes,
+ (trustedTypes) => {
+ if (trustedTypes === true) return {};
+ if (typeof trustedTypes === "string") {
+ return { policyName: trustedTypes };
+ }
+ return { ...trustedTypes };
}
- return { ...trustedTypes };
- }),
+ ),
uniqueName: output.uniqueName,
wasmLoading: output.wasmLoading,
webassemblyModuleFilename: output.webassemblyModuleFilename,
@@ -401,13 +404,13 @@ const getNormalizedWebpackOptions = config => ({
return result;
}),
parallelism: config.parallelism,
- performance: optionalNestedConfig(config.performance, performance => {
+ performance: optionalNestedConfig(config.performance, (performance) => {
if (performance === false) return false;
return {
...performance
};
}),
- plugins: /** @type {Plugins} */ (nestedArray(config.plugins, p => [...p])),
+ plugins: /** @type {Plugins} */ (nestedArray(config.plugins, (p) => [...p])),
profile: config.profile,
recordsInputPath:
config.recordsInputPath !== undefined
@@ -417,39 +420,39 @@ const getNormalizedWebpackOptions = config => ({
config.recordsOutputPath !== undefined
? config.recordsOutputPath
: config.recordsPath,
- resolve: nestedConfig(config.resolve, resolve => ({
+ resolve: nestedConfig(config.resolve, (resolve) => ({
...resolve,
byDependency: keyedNestedConfig(resolve.byDependency, cloneObject)
})),
resolveLoader: cloneObject(config.resolveLoader),
- snapshot: nestedConfig(config.snapshot, snapshot => ({
+ snapshot: nestedConfig(config.snapshot, (snapshot) => ({
resolveBuildDependencies: optionalNestedConfig(
snapshot.resolveBuildDependencies,
- resolveBuildDependencies => ({
+ (resolveBuildDependencies) => ({
timestamp: resolveBuildDependencies.timestamp,
hash: resolveBuildDependencies.hash
})
),
buildDependencies: optionalNestedConfig(
snapshot.buildDependencies,
- buildDependencies => ({
+ (buildDependencies) => ({
timestamp: buildDependencies.timestamp,
hash: buildDependencies.hash
})
),
- resolve: optionalNestedConfig(snapshot.resolve, resolve => ({
+ resolve: optionalNestedConfig(snapshot.resolve, (resolve) => ({
timestamp: resolve.timestamp,
hash: resolve.hash
})),
- module: optionalNestedConfig(snapshot.module, module => ({
+ module: optionalNestedConfig(snapshot.module, (module) => ({
timestamp: module.timestamp,
hash: module.hash
})),
- immutablePaths: optionalNestedArray(snapshot.immutablePaths, p => [...p]),
- managedPaths: optionalNestedArray(snapshot.managedPaths, p => [...p]),
- unmanagedPaths: optionalNestedArray(snapshot.unmanagedPaths, p => [...p])
+ immutablePaths: optionalNestedArray(snapshot.immutablePaths, (p) => [...p]),
+ managedPaths: optionalNestedArray(snapshot.managedPaths, (p) => [...p]),
+ unmanagedPaths: optionalNestedArray(snapshot.unmanagedPaths, (p) => [...p])
})),
- stats: nestedConfig(config.stats, stats => {
+ stats: nestedConfig(config.stats, (stats) => {
if (stats === false) {
return {
preset: "none"
@@ -478,7 +481,7 @@ const getNormalizedWebpackOptions = config => ({
* @param {EntryStatic} entry static entry options
* @returns {EntryStaticNormalized} normalized static entry options
*/
-const getNormalizedEntryStatic = entry => {
+const getNormalizedEntryStatic = (entry) => {
if (typeof entry === "string") {
return {
main: {
@@ -540,7 +543,7 @@ const getNormalizedEntryStatic = entry => {
* @param {OptimizationRuntimeChunk=} runtimeChunk runtimeChunk option
* @returns {OptimizationRuntimeChunkNormalized=} normalized runtimeChunk option
*/
-const getNormalizedOptimizationRuntimeChunk = runtimeChunk => {
+const getNormalizedOptimizationRuntimeChunk = (runtimeChunk) => {
if (runtimeChunk === undefined) return;
if (runtimeChunk === false) return false;
if (runtimeChunk === "single") {
@@ -550,7 +553,7 @@ const getNormalizedOptimizationRuntimeChunk = runtimeChunk => {
}
if (runtimeChunk === true || runtimeChunk === "multiple") {
return {
- name: entrypoint => `runtime~${entrypoint.name}`
+ name: (entrypoint) => `runtime~${entrypoint.name}`
};
}
const { name } = runtimeChunk;
diff --git a/lib/config/target.js b/lib/config/target.js
index 235019d665c..e8bb48d0069 100644
--- a/lib/config/target.js
+++ b/lib/config/target.js
@@ -15,7 +15,7 @@ const getBrowserslistTargetHandler = memoize(() =>
* @param {string} context the context directory
* @returns {string} default target
*/
-const getDefaultTarget = context => {
+const getDefaultTarget = (context) => {
const browsers = getBrowserslistTargetHandler().load(null, context);
return browsers ? "browserslist" : "web";
};
@@ -287,7 +287,7 @@ You can also more options via the 'target' option: 'browserslist' / 'browserslis
"esX",
"EcmaScript in this version. Examples: es2020, es5.",
/^es(\d+)$/,
- version => {
+ (version) => {
let v = Number(version);
if (v < 1000) v += 2009;
return {
@@ -333,7 +333,7 @@ const getTargetProperties = (target, context) => {
* @param {TargetProperties[]} targetProperties array of target properties
* @returns {TargetProperties} merged target properties
*/
-const mergeTargetProperties = targetProperties => {
+const mergeTargetProperties = (targetProperties) => {
/** @type {Set} */
const keys = new Set();
for (const tp of targetProperties) {
@@ -371,7 +371,7 @@ const mergeTargetProperties = targetProperties => {
* @returns {TargetProperties} target properties
*/
const getTargetsProperties = (targets, context) =>
- mergeTargetProperties(targets.map(t => getTargetProperties(t, context)));
+ mergeTargetProperties(targets.map((t) => getTargetProperties(t, context)));
module.exports.getDefaultTarget = getDefaultTarget;
module.exports.getTargetProperties = getTargetProperties;
diff --git a/lib/container/ContainerEntryModule.js b/lib/container/ContainerEntryModule.js
index 0395372e84e..37a2298491e 100644
--- a/lib/container/ContainerEntryModule.js
+++ b/lib/container/ContainerEntryModule.js
@@ -159,7 +159,7 @@ class ContainerEntryModule extends Module {
for (const block of this.blocks) {
const { dependencies } = block;
- const modules = dependencies.map(dependency => {
+ const modules = dependencies.map((dependency) => {
const dep = /** @type {ContainerExposedDependency} */ (dependency);
return {
name: dep.exposedName,
@@ -170,9 +170,9 @@ class ContainerEntryModule extends Module {
let str;
- if (modules.some(m => !m.module)) {
+ if (modules.some((m) => !m.module)) {
str = runtimeTemplate.throwMissingModuleErrorBlock({
- request: modules.map(m => m.request).join(", ")
+ request: modules.map((m) => m.request).join(", ")
});
} else {
str = `return ${runtimeTemplate.blockPromise({
diff --git a/lib/container/ContainerPlugin.js b/lib/container/ContainerPlugin.js
index 9a497fc5ad8..7a725dc844c 100644
--- a/lib/container/ContainerPlugin.js
+++ b/lib/container/ContainerPlugin.js
@@ -51,11 +51,11 @@ class ContainerPlugin {
exposes: /** @type {ExposesList} */ (
parseOptions(
options.exposes,
- item => ({
+ (item) => ({
import: Array.isArray(item) ? item : [item],
name: undefined
}),
- item => ({
+ (item) => ({
import: Array.isArray(item.import) ? item.import : [item.import],
name: item.name || undefined
})
@@ -91,7 +91,7 @@ class ContainerPlugin {
runtime,
library
},
- error => {
+ (error) => {
if (error) return callback(error);
hooks.addContainerEntryDependency.call(dep);
callback();
diff --git a/lib/container/ContainerReferencePlugin.js b/lib/container/ContainerReferencePlugin.js
index 207329afe61..95efc51b99d 100644
--- a/lib/container/ContainerReferencePlugin.js
+++ b/lib/container/ContainerReferencePlugin.js
@@ -43,11 +43,11 @@ class ContainerReferencePlugin {
this._remoteType = options.remoteType;
this._remotes = parseOptions(
options.remotes,
- item => ({
+ (item) => ({
external: Array.isArray(item) ? item : [item],
shareScope: options.shareScope || "default"
}),
- item => ({
+ (item) => ({
external: Array.isArray(item.external)
? item.external
: [item.external],
@@ -97,7 +97,7 @@ class ContainerReferencePlugin {
new FallbackModuleFactory()
);
- normalModuleFactory.hooks.factorize.tap(PLUGIN_NAME, data => {
+ normalModuleFactory.hooks.factorize.tap(PLUGIN_NAME, (data) => {
if (!data.request.includes("!")) {
for (const [key, config] of remotes) {
if (
diff --git a/lib/container/FallbackModule.js b/lib/container/FallbackModule.js
index 7e0be846aa9..be757f0e061 100644
--- a/lib/container/FallbackModule.js
+++ b/lib/container/FallbackModule.js
@@ -131,7 +131,7 @@ class FallbackModule extends Module {
* @returns {CodeGenerationResult} result
*/
codeGeneration({ runtimeTemplate, moduleGraph, chunkGraph }) {
- const ids = this.dependencies.map(dep =>
+ const ids = this.dependencies.map((dep) =>
chunkGraph.getModuleId(/** @type {Module} */ (moduleGraph.getModule(dep)))
);
const code = Template.asString([
diff --git a/lib/container/HoistContainerReferencesPlugin.js b/lib/container/HoistContainerReferencesPlugin.js
index 669dcccddca..238bb32805b 100644
--- a/lib/container/HoistContainerReferencesPlugin.js
+++ b/lib/container/HoistContainerReferencesPlugin.js
@@ -31,19 +31,19 @@ class HoistContainerReferences {
* @param {Compiler} compiler The webpack compiler instance.
*/
apply(compiler) {
- compiler.hooks.thisCompilation.tap(PLUGIN_NAME, compilation => {
+ compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {
const hooks =
getModuleFederationPlugin().getCompilationHooks(compilation);
const depsToTrace = new Set();
const entryExternalsToHoist = new Set();
- hooks.addContainerEntryDependency.tap(PLUGIN_NAME, dep => {
+ hooks.addContainerEntryDependency.tap(PLUGIN_NAME, (dep) => {
depsToTrace.add(dep);
});
- hooks.addFederationRuntimeDependency.tap(PLUGIN_NAME, dep => {
+ hooks.addFederationRuntimeDependency.tap(PLUGIN_NAME, (dep) => {
depsToTrace.add(dep);
});
- compilation.hooks.addEntry.tap(PLUGIN_NAME, entryDep => {
+ compilation.hooks.addEntry.tap(PLUGIN_NAME, (entryDep) => {
if (entryDep.type === "entry") {
entryExternalsToHoist.add(entryDep);
}
@@ -56,7 +56,7 @@ class HoistContainerReferences {
// advanced stage is where SplitChunksPlugin runs.
stage: STAGE_ADVANCED + 1
},
- _chunks => {
+ (_chunks) => {
this.hoistModulesInChunks(
compilation,
depsToTrace,
@@ -92,7 +92,7 @@ class HoistContainerReferences {
const runtimes = new Set();
for (const runtimeSpec of containerRuntimes) {
- forEachRuntime(runtimeSpec, runtimeKey => {
+ forEachRuntime(runtimeSpec, (runtimeKey) => {
if (runtimeKey) {
runtimes.add(runtimeKey);
}
@@ -139,7 +139,7 @@ class HoistContainerReferences {
const runtimes = new Set();
for (const runtimeSpec of containerRuntimes) {
- forEachRuntime(runtimeSpec, runtimeKey => {
+ forEachRuntime(runtimeSpec, (runtimeKey) => {
if (runtimeKey) {
runtimes.add(runtimeKey);
}
diff --git a/lib/container/options.js b/lib/container/options.js
index 367d622613e..953aea64c76 100644
--- a/lib/container/options.js
+++ b/lib/container/options.js
@@ -28,7 +28,7 @@ const process = (options, normalizeSimple, normalizeOptions, fn) => {
/**
* @param {(string | Item)[]} items items
*/
- const array = items => {
+ const array = (items) => {
for (const item of items) {
if (typeof item === "string") {
fn(item, normalizeSimple(item, item));
@@ -42,7 +42,7 @@ const process = (options, normalizeSimple, normalizeOptions, fn) => {
/**
* @param {Item} obj an object
*/
- const object = obj => {
+ const object = (obj) => {
for (const [key, value] of Object.entries(obj)) {
if (typeof value === "string" || Array.isArray(value)) {
fn(key, normalizeSimple(value, key));
@@ -90,8 +90,8 @@ const scope = (scope, options) => {
const obj = {};
process(
options,
- item => /** @type {string | string[] | T} */ (item),
- item => /** @type {string | string[] | T} */ (item),
+ (item) => /** @type {string | string[] | T} */ (item),
+ (item) => /** @type {string | string[] | T} */ (item),
(key, value) => {
obj[
key.startsWith("./") ? `${scope}${key.slice(1)}` : `${scope}/${key}`
diff --git a/lib/css/CssGenerator.js b/lib/css/CssGenerator.js
index a40ca9ad59f..56cbc5d607f 100644
--- a/lib/css/CssGenerator.js
+++ b/lib/css/CssGenerator.js
@@ -18,6 +18,7 @@ const {
} = require("../ModuleSourceTypesConstants");
const RuntimeGlobals = require("../RuntimeGlobals");
const Template = require("../Template");
+const memoize = require("../util/memoize");
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../../declarations/WebpackOptions").CssAutoGeneratorOptions} CssAutoGeneratorOptions */
@@ -37,6 +38,8 @@ const Template = require("../Template");
/** @typedef {import("../NormalModule")} NormalModule */
/** @typedef {import("../util/Hash")} Hash */
+const getPropertyName = memoize(() => require("../util/propertyName"));
+
class CssGenerator extends Generator {
/**
* @param {CssAutoGeneratorOptions | CssGlobalGeneratorOptions | CssModuleGeneratorOptions} options options
@@ -119,7 +122,7 @@ class CssGenerator extends Generator {
/**
* @param {Dependency} dependency dependency
*/
- const handleDependency = dependency => {
+ const handleDependency = (dependency) => {
const constructor =
/** @type {new (...args: EXPECTED_ANY[]) => Dependency} */
(dependency.constructor);
@@ -147,6 +150,7 @@ class CssGenerator extends Generator {
if (generateContext.concatenationScope) {
const source = new ConcatSource();
const usedIdentifiers = new Set();
+ const { RESERVED_IDENTIFIER } = getPropertyName();
for (const [name, v] of cssData.exports) {
const usedName = generateContext.moduleGraph
.getExportInfo(module, name)
@@ -156,8 +160,6 @@ class CssGenerator extends Generator {
}
let identifier = Template.toIdentifier(usedName);
- const { RESERVED_IDENTIFIER } = require("../util/propertyName");
-
if (RESERVED_IDENTIFIER.has(identifier)) {
identifier = `_${identifier}`;
}
diff --git a/lib/css/CssLoadingRuntimeModule.js b/lib/css/CssLoadingRuntimeModule.js
index 1c46eebe552..ce2a9b13d88 100644
--- a/lib/css/CssLoadingRuntimeModule.js
+++ b/lib/css/CssLoadingRuntimeModule.js
@@ -181,7 +181,7 @@ class CssLoadingRuntimeModule extends RuntimeModule {
stateExpression ? `${stateExpression} = ${stateExpression} || ` : ""
}{`,
Template.indent(
- Array.from(initialChunkIds, id => `${JSON.stringify(id)}: 0`).join(
+ Array.from(initialChunkIds, (id) => `${JSON.stringify(id)}: 0`).join(
",\n"
)
),
diff --git a/lib/css/CssModulesPlugin.js b/lib/css/CssModulesPlugin.js
index 9dfc70d897b..9c5be4c1387 100644
--- a/lib/css/CssModulesPlugin.js
+++ b/lib/css/CssModulesPlugin.js
@@ -98,7 +98,7 @@ const getCssLoadingRuntimeModule = memoize(() =>
* @param {string} name name
* @returns {{ oneOf: [{ $ref: string }], definitions: import("../../schemas/WebpackOptions.json")["definitions"] }} schema
*/
-const getSchema = name => {
+const getSchema = (name) => {
const { definitions } = require("../../schemas/WebpackOptions.json");
return {
@@ -264,7 +264,7 @@ class CssModulesPlugin {
]) {
normalModuleFactory.hooks.createParser
.for(type)
- .tap(PLUGIN_NAME, parserOptions => {
+ .tap(PLUGIN_NAME, (parserOptions) => {
validateParserOptions[type](parserOptions);
const { url, import: importOption, namedExports } = parserOptions;
@@ -300,7 +300,7 @@ class CssModulesPlugin {
});
normalModuleFactory.hooks.createGenerator
.for(type)
- .tap(PLUGIN_NAME, generatorOptions => {
+ .tap(PLUGIN_NAME, (generatorOptions) => {
validateGeneratorOptions[type](generatorOptions);
return new CssGenerator(
@@ -442,7 +442,7 @@ class CssModulesPlugin {
compilation.hooks.chunkHash.tap(PLUGIN_NAME, (chunk, hash, context) => {
hooks.chunkHash.call(chunk, hash, context);
});
- compilation.hooks.contentHash.tap(PLUGIN_NAME, chunk => {
+ compilation.hooks.contentHash.tap(PLUGIN_NAME, (chunk) => {
const {
chunkGraph,
codeGenerationResults,
@@ -533,7 +533,7 @@ class CssModulesPlugin {
* @param {Chunk} chunk the chunk
* @returns {boolean} true, when enabled
*/
- const isEnabledForChunk = chunk => {
+ const isEnabledForChunk = (chunk) => {
const options = chunk.getEntryOptions();
const chunkLoading =
options && options.chunkLoading !== undefined
@@ -566,7 +566,7 @@ class CssModulesPlugin {
if (
!chunkGraph.hasModuleInGraph(
chunk,
- m =>
+ (m) =>
m.type === CSS_MODULE_TYPE ||
m.type === CSS_MODULE_TYPE_GLOBAL ||
m.type === CSS_MODULE_TYPE_MODULE ||
@@ -587,7 +587,7 @@ class CssModulesPlugin {
if (
!chunkGraph.hasModuleInGraph(
chunk,
- m =>
+ (m) =>
m.type === CSS_MODULE_TYPE ||
m.type === CSS_MODULE_TYPE_GLOBAL ||
m.type === CSS_MODULE_TYPE_MODULE ||
@@ -617,21 +617,24 @@ class CssModulesPlugin {
// Get ordered list of modules per chunk group
// Lists are in reverse order to allow to use Array.pop()
- const modulesByChunkGroup = Array.from(chunk.groupsIterable, chunkGroup => {
- const sortedModules = modulesList
- .map(module => ({
- module,
- index: chunkGroup.getModulePostOrderIndex(module)
- }))
- .filter(item => item.index !== undefined)
- .sort(
- (a, b) =>
- /** @type {number} */ (b.index) - /** @type {number} */ (a.index)
- )
- .map(item => item.module);
-
- return { list: sortedModules, set: new Set(sortedModules) };
- });
+ const modulesByChunkGroup = Array.from(
+ chunk.groupsIterable,
+ (chunkGroup) => {
+ const sortedModules = modulesList
+ .map((module) => ({
+ module,
+ index: chunkGroup.getModulePostOrderIndex(module)
+ }))
+ .filter((item) => item.index !== undefined)
+ .sort(
+ (a, b) =>
+ /** @type {number} */ (b.index) - /** @type {number} */ (a.index)
+ )
+ .map((item) => item.module);
+
+ return { list: sortedModules, set: new Set(sortedModules) };
+ }
+ );
if (modulesByChunkGroup.length === 1) {
return modulesByChunkGroup[0].list.reverse();
diff --git a/lib/css/CssParser.js b/lib/css/CssParser.js
index 7d19ba4def3..b8b430bc7a7 100644
--- a/lib/css/CssParser.js
+++ b/lib/css/CssParser.js
@@ -76,7 +76,7 @@ const normalizeUrl = (str, isString) => {
// Remove unnecessary spaces from `url(" img.png ")`
.replace(TRIM_WHITE_SPACES, "")
// Unescape
- .replace(UNESCAPE, match => {
+ .replace(UNESCAPE, (match) => {
if (match.length > 2) {
return String.fromCharCode(Number.parseInt(match.slice(1).trim(), 16));
}
@@ -108,7 +108,7 @@ const regexExcessiveSpaces =
* @param {string} str string
* @returns {string} escaped identifier
*/
-const escapeIdentifier = str => {
+const escapeIdentifier = (str) => {
let output = "";
let counter = 0;
@@ -161,7 +161,7 @@ const CONTAINS_ESCAPE = /\\/;
* @param {string} str string
* @returns {[string, number] | undefined} hex
*/
-const gobbleHex = str => {
+const gobbleHex = (str) => {
const lower = str.toLowerCase();
let hex = "";
let spaceTerminated = false;
@@ -198,7 +198,7 @@ const gobbleHex = str => {
* @param {string} str string
* @returns {string} unescaped string
*/
-const unescapeIdentifier = str => {
+const unescapeIdentifier = (str) => {
const needToProcess = CONTAINS_ESCAPE.test(str);
if (!needToProcess) return str;
let ret = "";
@@ -646,7 +646,7 @@ class CssParser extends Parser {
/**
* @param {string} input input
*/
- const processDeclarationValueDone = input => {
+ const processDeclarationValueDone = (input) => {
if (inAnimationProperty && lastIdentifier) {
const { line: sl, column: sc } = locConverter.get(lastIdentifier[0]);
const { line: el, column: ec } = locConverter.get(lastIdentifier[1]);
diff --git a/lib/css/walkCssTokens.js b/lib/css/walkCssTokens.js
index f6b8b042bda..bfdc05b10e2 100644
--- a/lib/css/walkCssTokens.js
+++ b/lib/css/walkCssTokens.js
@@ -98,7 +98,7 @@ const consumeSpace = (input, pos, _callbacks) => {
* @param {number} cc char code
* @returns {boolean} true, if cc is a newline
*/
-const _isNewline = cc =>
+const _isNewline = (cc) =>
cc === CC_LINE_FEED || cc === CC_CARRIAGE_RETURN || cc === CC_FORM_FEED;
/**
@@ -119,13 +119,13 @@ const consumeExtraNewline = (cc, input, pos) => {
* @param {number} cc char code
* @returns {boolean} true, if cc is a space (U+0009 CHARACTER TABULATION or U+0020 SPACE)
*/
-const _isSpace = cc => cc === CC_TAB || cc === CC_SPACE;
+const _isSpace = (cc) => cc === CC_TAB || cc === CC_SPACE;
/**
* @param {number} cc char code
* @returns {boolean} true, if cc is a whitespace
*/
-const _isWhiteSpace = cc => _isNewline(cc) || _isSpace(cc);
+const _isWhiteSpace = (cc) => _isNewline(cc) || _isSpace(cc);
/**
* ident-start code point
@@ -134,7 +134,7 @@ const _isWhiteSpace = cc => _isNewline(cc) || _isSpace(cc);
* @param {number} cc char code
* @returns {boolean} true, if cc is a start code point of an identifier
*/
-const isIdentStartCodePoint = cc =>
+const isIdentStartCodePoint = (cc) =>
(cc >= CC_LOWER_A && cc <= CC_LOWER_Z) ||
(cc >= CC_UPPER_A && cc <= CC_UPPER_Z) ||
cc === CC_LOW_LINE ||
@@ -189,7 +189,7 @@ const consumeComments = (input, pos, callbacks) => {
* @param {number} cc char code
* @returns {boolean} true, if cc is a hex digit
*/
-const _isHexDigit = cc =>
+const _isHexDigit = (cc) =>
_isDigit(cc) ||
(cc >= CC_UPPER_A && cc <= CC_UPPER_F) ||
(cc >= CC_LOWER_A && cc <= CC_LOWER_F);
@@ -325,7 +325,7 @@ const isNonASCIICodePoint = (cc, q) =>
* @param {number} cc char code
* @returns {boolean} is letter
*/
-const isLetter = cc =>
+const isLetter = (cc) =>
(cc >= CC_LOWER_A && cc <= CC_LOWER_Z) ||
(cc >= CC_UPPER_A && cc <= CC_UPPER_Z);
@@ -348,7 +348,7 @@ const _isIdentCodePoint = (cc, q) =>
* @param {number} cc char code
* @returns {boolean} is digit
*/
-const _isDigit = cc => cc >= CC_0 && cc <= CC_9;
+const _isDigit = (cc) => cc >= CC_0 && cc <= CC_9;
/**
* @param {string} input input
@@ -799,7 +799,7 @@ const _consumeAnIdentSequence = (input, pos) => {
* @param {number} cc char code
* @returns {boolean} true, when cc is the non-printable code point, otherwise false
*/
-const _isNonPrintableCodePoint = cc =>
+const _isNonPrintableCodePoint = (cc) =>
(cc >= 0x00 && cc <= 0x08) ||
cc === 0x0b ||
(cc >= 0x0e && cc <= 0x1f) ||
@@ -1584,7 +1584,7 @@ const eatIdentSequenceOrString = (input, pos) => {
* @param {string} chars characters
* @returns {(input: string, pos: number) => number} function to eat characters
*/
-const eatUntil = chars => {
+const eatUntil = (chars) => {
const charCodes = Array.from({ length: chars.length }, (_, i) =>
chars.charCodeAt(i)
);
diff --git a/lib/debug/ProfilingPlugin.js b/lib/debug/ProfilingPlugin.js
index 7a0f648217b..eff5240ae09 100644
--- a/lib/debug/ProfilingPlugin.js
+++ b/lib/debug/ProfilingPlugin.js
@@ -203,7 +203,7 @@ const createTrace = (fs, outputPath) => {
trace,
counter,
profiler,
- end: callback => {
+ end: (callback) => {
trace.push("]");
// Wait until the write stream finishes.
fsStream.on("close", () => {
@@ -288,7 +288,7 @@ class ProfilingPlugin {
},
(stats, callback) => {
if (compiler.watchMode) return callback();
- tracer.profiler.stopProfiling().then(parsedResults => {
+ tracer.profiler.stopProfiling().then((parsedResults) => {
if (parsedResults === undefined) {
tracer.profiler.destroy();
tracer.end(callback);
@@ -443,12 +443,12 @@ const interceptAllCssModulesPluginHooks = (compilation, tracer) => {
* @param {Trace} tracer tracer
* @returns {(hookName: string) => TODO} interceptor
*/
-const makeInterceptorFor = (instance, tracer) => hookName => ({
+const makeInterceptorFor = (instance, tracer) => (hookName) => ({
/**
* @param {FullTap} tapInfo tap info
* @returns {FullTap} modified full tap
*/
- register: tapInfo => {
+ register: (tapInfo) => {
const { name, type, fn: internalFn } = tapInfo;
const newFn =
// Don't tap our own hooks to ensure stream can close cleanly
@@ -487,7 +487,7 @@ const makeNewProfiledTapFn = (hookName, tracer, { name, type, fn }) => {
const promise =
/** @type {Promise<(...args: EXPECTED_ANY[]) => EXPECTED_ANY>} */
(fn(...args));
- return promise.then(r => {
+ return promise.then((r) => {
tracer.trace.end({
name,
id,
diff --git a/lib/dependencies/AMDDefineDependencyParserPlugin.js b/lib/dependencies/AMDDefineDependencyParserPlugin.js
index 43bb2763e30..56cab2a8219 100644
--- a/lib/dependencies/AMDDefineDependencyParserPlugin.js
+++ b/lib/dependencies/AMDDefineDependencyParserPlugin.js
@@ -36,7 +36,7 @@ const { addLocalModule, getLocalModule } = require("./LocalModulesHelpers");
* @param {Expression | SpreadElement} expr expression
* @returns {expr is CallExpression} true if it's a bound function expression
*/
-const isBoundFunctionExpression = expr => {
+const isBoundFunctionExpression = (expr) => {
if (expr.type !== "CallExpression") return false;
if (expr.callee.type !== "MemberExpression") return false;
if (expr.callee.computed) return false;
@@ -52,7 +52,7 @@ const isBoundFunctionExpression = expr => {
* @param {Expression | SpreadElement} expr expression
* @returns {expr is FunctionExpression | ArrowFunctionExpression} true when unbound function expression
*/
-const isUnboundFunctionExpression = expr => {
+const isUnboundFunctionExpression = (expr) => {
if (expr.type === "FunctionExpression") return true;
if (expr.type === "ArrowFunctionExpression") return true;
return false;
@@ -62,7 +62,7 @@ const isUnboundFunctionExpression = expr => {
* @param {Expression | SpreadElement} expr expression
* @returns {expr is FunctionExpression | ArrowFunctionExpression | CallExpression} true when callable
*/
-const isCallable = expr => {
+const isCallable = (expr) => {
if (isUnboundFunctionExpression(expr)) return true;
if (isBoundFunctionExpression(expr)) return true;
return false;
@@ -410,7 +410,7 @@ class AMDDefineDependencyParserPlugin {
parser.inScope(
/** @type {Identifier[]} */
(object.params).filter(
- i => !["require", "module", "exports"].includes(i.name)
+ (i) => !["require", "module", "exports"].includes(i.name)
),
() => {
for (const [name, varInfo] of fnRenames) {
diff --git a/lib/dependencies/AMDPlugin.js b/lib/dependencies/AMDPlugin.js
index 9c8a12f6a0a..add34161d7d 100644
--- a/lib/dependencies/AMDPlugin.js
+++ b/lib/dependencies/AMDPlugin.js
@@ -156,7 +156,7 @@ class AMDPlugin {
);
parser.hooks.evaluateIdentifier
.for(optionExpr)
- .tap(PLUGIN_NAME, expr =>
+ .tap(PLUGIN_NAME, (expr) =>
evaluateToIdentifier(
optionExpr,
rootName,
@@ -188,7 +188,7 @@ class AMDPlugin {
() => []
);
- parser.hooks.expression.for("define").tap(PLUGIN_NAME, expr => {
+ parser.hooks.expression.for("define").tap(PLUGIN_NAME, (expr) => {
const dep = new ConstDependency(
RuntimeGlobals.amdDefine,
/** @type {Range} */ (expr.range),
@@ -208,7 +208,7 @@ class AMDPlugin {
.for("define")
.tap(PLUGIN_NAME, evaluateToString("function"));
parser.hooks.canRename.for("define").tap(PLUGIN_NAME, approve);
- parser.hooks.rename.for("define").tap(PLUGIN_NAME, expr => {
+ parser.hooks.rename.for("define").tap(PLUGIN_NAME, (expr) => {
const dep = new ConstDependency(
RuntimeGlobals.amdDefine,
/** @type {Range} */ (expr.range),
diff --git a/lib/dependencies/AMDRequireArrayDependency.js b/lib/dependencies/AMDRequireArrayDependency.js
index 1df80723d10..0740025fefa 100644
--- a/lib/dependencies/AMDRequireArrayDependency.js
+++ b/lib/dependencies/AMDRequireArrayDependency.js
@@ -89,7 +89,7 @@ AMDRequireArrayDependency.Template = class AMDRequireArrayDependencyTemplate ext
* @returns {string} content
*/
getContent(dep, templateContext) {
- const requires = dep.depsArray.map(dependency =>
+ const requires = dep.depsArray.map((dependency) =>
this.contentForDependency(dependency, templateContext)
);
return `[${requires.join(", ")}]`;
diff --git a/lib/dependencies/AMDRequireDependenciesBlockParserPlugin.js b/lib/dependencies/AMDRequireDependenciesBlockParserPlugin.js
index e0bbf60b926..0d28b8b9f17 100644
--- a/lib/dependencies/AMDRequireDependenciesBlockParserPlugin.js
+++ b/lib/dependencies/AMDRequireDependenciesBlockParserPlugin.js
@@ -52,7 +52,7 @@ class AMDRequireDependenciesBlockParserPlugin {
if (fnData) {
parser.inScope(
fnData.fn.params.filter(
- i =>
+ (i) =>
!["require", "module", "exports"].includes(
/** @type {Identifier} */ (i).name
)
@@ -236,7 +236,7 @@ class AMDRequireDependenciesBlockParserPlugin {
if (param.isArray()) {
const result =
/** @type {BasicEvaluatedExpression[]} */
- (param.items).map(item => this.processItemForRequestString(item));
+ (param.items).map((item) => this.processItemForRequestString(item));
if (result.every(Boolean)) return result.join(" ");
} else if (param.isConstArray()) {
return /** @type {string[]} */ (param.array).join(" ");
@@ -251,7 +251,7 @@ class AMDRequireDependenciesBlockParserPlugin {
if (param.isConditional()) {
const result =
/** @type {BasicEvaluatedExpression[]} */
- (param.options).map(item => this.processItemForRequestString(item));
+ (param.options).map((item) => this.processItemForRequestString(item));
if (result.every(Boolean)) return result.join("|");
} else if (param.isString()) {
return param.string;
diff --git a/lib/dependencies/CommonJsExportRequireDependency.js b/lib/dependencies/CommonJsExportRequireDependency.js
index 3f7c66cf3bc..fc16baab9e1 100644
--- a/lib/dependencies/CommonJsExportRequireDependency.js
+++ b/lib/dependencies/CommonJsExportRequireDependency.js
@@ -131,7 +131,7 @@ class CommonJsExportRequireDependency extends ModuleDependency {
false
);
}
- return referencedExports.map(name => ({
+ return referencedExports.map((name) => ({
name,
canMangle: false
}));
@@ -190,7 +190,7 @@ class CommonJsExportRequireDependency extends ModuleDependency {
exports: Array.from(
/** @type {Set} */
(reexportInfo.exports),
- name => ({
+ (name) => ({
name,
from,
export: [...ids, name],
diff --git a/lib/dependencies/CommonJsExportsParserPlugin.js b/lib/dependencies/CommonJsExportsParserPlugin.js
index 400882c2999..2592aa9816b 100644
--- a/lib/dependencies/CommonJsExportsParserPlugin.js
+++ b/lib/dependencies/CommonJsExportsParserPlugin.js
@@ -47,7 +47,7 @@ const ModuleDecoratorDependency = require("./ModuleDecoratorDependency");
* @param {Expression} expr expression
* @returns {Expression | undefined} returns the value of property descriptor
*/
-const getValueOfPropertyDescription = expr => {
+const getValueOfPropertyDescription = (expr) => {
if (expr.type !== "ObjectExpression") return;
for (const property of expr.properties) {
if (property.type === "SpreadElement" || property.computed) continue;
@@ -64,7 +64,7 @@ const getValueOfPropertyDescription = expr => {
* @param {Expression} expr expression being checked
* @returns {boolean} true, when the expression is a truthy literal
*/
-const isTruthyLiteral = expr => {
+const isTruthyLiteral = (expr) => {
switch (expr.type) {
case "Literal":
return Boolean(expr.value);
@@ -81,7 +81,7 @@ const isTruthyLiteral = expr => {
* @param {Expression} expr expression being checked
* @returns {boolean} true, when the expression is a falsy literal
*/
-const isFalsyLiteral = expr => {
+const isFalsyLiteral = (expr) => {
switch (expr.type) {
case "Literal":
return !expr.value;
@@ -163,14 +163,14 @@ class CommonJsExportsParserPlugin {
/**
* @param {string=} reason reason
*/
- const bailout = reason => {
+ const bailout = (reason) => {
DynamicExports.bailout(parser.state);
if (reason) bailoutHint(reason);
};
/**
* @param {string} reason reason
*/
- const bailoutHint = reason => {
+ const bailoutHint = (reason) => {
this.moduleGraph
.getOptimizationBailout(parser.state.module)
.push(`CommonJS bailout: ${reason}`);
@@ -258,7 +258,7 @@ class CommonJsExportsParserPlugin {
});
parser.hooks.call
.for("Object.defineProperty")
- .tap(PLUGIN_NAME, expression => {
+ .tap(PLUGIN_NAME, (expression) => {
const expr = /** @type {CallExpression} */ (expression);
if (!parser.isStatementLevelExpression(expr)) return;
if (expr.arguments.length !== 3) return;
@@ -350,7 +350,7 @@ class CommonJsExportsParserPlugin {
);
parser.hooks.expression
.for("exports")
- .tap(PLUGIN_NAME, expr => handleAccessExport(expr, "exports", []));
+ .tap(PLUGIN_NAME, (expr) => handleAccessExport(expr, "exports", []));
parser.hooks.callMemberChain
.for("module")
.tap(PLUGIN_NAME, (expr, members) => {
@@ -370,7 +370,9 @@ class CommonJsExportsParserPlugin {
});
parser.hooks.expression
.for("module.exports")
- .tap(PLUGIN_NAME, expr => handleAccessExport(expr, "module.exports", []));
+ .tap(PLUGIN_NAME, (expr) =>
+ handleAccessExport(expr, "module.exports", [])
+ );
parser.hooks.callMemberChain
.for("this")
.tap(PLUGIN_NAME, (expr, members) => {
@@ -383,13 +385,13 @@ class CommonJsExportsParserPlugin {
if (!parser.scope.topLevelScope) return;
return handleAccessExport(expr, "this", members);
});
- parser.hooks.expression.for("this").tap(PLUGIN_NAME, expr => {
+ parser.hooks.expression.for("this").tap(PLUGIN_NAME, (expr) => {
if (!parser.scope.topLevelScope) return;
return handleAccessExport(expr, "this", []);
});
// Bailouts //
- parser.hooks.expression.for("module").tap(PLUGIN_NAME, expr => {
+ parser.hooks.expression.for("module").tap(PLUGIN_NAME, (expr) => {
bailout();
const isHarmony = HarmonyExports.isEnabled(parser.state);
const dep = new ModuleDecoratorDependency(
diff --git a/lib/dependencies/CommonJsImportsParserPlugin.js b/lib/dependencies/CommonJsImportsParserPlugin.js
index 82962ce7cda..9bb81115c81 100644
--- a/lib/dependencies/CommonJsImportsParserPlugin.js
+++ b/lib/dependencies/CommonJsImportsParserPlugin.js
@@ -91,7 +91,7 @@ class CommonJsImportsParserPlugin {
/**
* @param {string | symbol} tag tag
*/
- const tapRequireExpressionTag = tag => {
+ const tapRequireExpressionTag = (tag) => {
parser.hooks.typeof
.for(tag)
.tap(
@@ -108,7 +108,7 @@ class CommonJsImportsParserPlugin {
// #endregion
// Weird stuff //
- parser.hooks.assign.for("require").tap(PLUGIN_NAME, expr => {
+ parser.hooks.assign.for("require").tap(PLUGIN_NAME, (expr) => {
// to not leak to global "require", we need to define a local require here.
const dep = new ConstDependency("var require;", 0);
dep.loc = /** @type {DependencyLocation} */ (expr.loc);
@@ -160,7 +160,7 @@ class CommonJsImportsParserPlugin {
* @param {Expression} expr expression
* @returns {boolean} true when set undefined
*/
- const defineUndefined = expr => {
+ const defineUndefined = (expr) => {
// To avoid "not defined" error, replace the value with undefined
const dep = new ConstDependency(
"undefined",
@@ -193,7 +193,7 @@ class CommonJsImportsParserPlugin {
* @param {Expression} expr expression
* @returns {boolean} true when handled
*/
- const requireAsExpressionHandler = expr => {
+ const requireAsExpressionHandler = (expr) => {
const dep = new CommonJsRequireContextDependency(
{
request: /** @type {string} */ (options.unknownContextRequest),
@@ -267,7 +267,7 @@ class CommonJsImportsParserPlugin {
* @param {boolean} callNew true, when require is called with new
* @returns {(expr: CallExpression | NewExpression) => (boolean | void)} handler
*/
- const createRequireHandler = callNew => expr => {
+ const createRequireHandler = (callNew) => (expr) => {
if (options.commonjsMagicComments) {
const { options: requireOptions, errors: commentErrors } =
parser.parseCommentOptions(/** @type {Range} */ (expr.range));
@@ -567,10 +567,10 @@ class CommonJsImportsParserPlugin {
parser.hooks.call
.for("require.resolve")
- .tap(PLUGIN_NAME, expr => processResolve(expr, false));
+ .tap(PLUGIN_NAME, (expr) => processResolve(expr, false));
parser.hooks.call
.for("require.resolveWeak")
- .tap(PLUGIN_NAME, expr => processResolve(expr, true));
+ .tap(PLUGIN_NAME, (expr) => processResolve(expr, true));
// #endregion
// #region Create require
@@ -607,7 +607,7 @@ class CommonJsImportsParserPlugin {
tapRequireExpressionTag(createRequireSpecifierTag);
parser.hooks.evaluateCallExpression
.for(createRequireSpecifierTag)
- .tap(PLUGIN_NAME, expr => {
+ .tap(PLUGIN_NAME, (expr) => {
const context = parseCreateRequireArguments(expr);
if (context === undefined) return;
const ident = parser.evaluatedVariable({
@@ -648,7 +648,7 @@ class CommonJsImportsParserPlugin {
* @param {CallExpression} expr call expression
* @returns {string | void} context
*/
- const parseCreateRequireArguments = expr => {
+ const parseCreateRequireArguments = (expr) => {
const args = expr.arguments;
if (args.length !== 1) {
const err = new WebpackError(
@@ -715,7 +715,7 @@ class CommonJsImportsParserPlugin {
return true;
}
);
- parser.hooks.preDeclarator.tap(PLUGIN_NAME, declarator => {
+ parser.hooks.preDeclarator.tap(PLUGIN_NAME, (declarator) => {
if (
declarator.id.type !== "Identifier" ||
!declarator.init ||
@@ -784,15 +784,17 @@ class CommonJsImportsParserPlugin {
return processResolve(expr, false);
}
});
- parser.hooks.call.for(createRequireSpecifierTag).tap(PLUGIN_NAME, expr => {
- const clearDep = new ConstDependency(
- "/* createRequire() */ undefined",
- /** @type {Range} */ (expr.range)
- );
- clearDep.loc = /** @type {DependencyLocation} */ (expr.loc);
- parser.state.module.addPresentationalDependency(clearDep);
- return true;
- });
+ parser.hooks.call
+ .for(createRequireSpecifierTag)
+ .tap(PLUGIN_NAME, (expr) => {
+ const clearDep = new ConstDependency(
+ "/* createRequire() */ undefined",
+ /** @type {Range} */ (expr.range)
+ );
+ clearDep.loc = /** @type {DependencyLocation} */ (expr.loc);
+ parser.state.module.addPresentationalDependency(clearDep);
+ return true;
+ });
// #endregion
}
}
diff --git a/lib/dependencies/CommonJsPlugin.js b/lib/dependencies/CommonJsPlugin.js
index 97b8695872a..194a16c77e5 100644
--- a/lib/dependencies/CommonJsPlugin.js
+++ b/lib/dependencies/CommonJsPlugin.js
@@ -200,7 +200,7 @@ class CommonJsPlugin {
);
parser.hooks.expression
.for(RuntimeGlobals.moduleLoaded)
- .tap(PLUGIN_NAME, expr => {
+ .tap(PLUGIN_NAME, (expr) => {
/** @type {BuildInfo} */
(parser.state.module.buildInfo).moduleConcatenationBailout =
RuntimeGlobals.moduleLoaded;
@@ -214,7 +214,7 @@ class CommonJsPlugin {
parser.hooks.expression
.for(RuntimeGlobals.moduleId)
- .tap(PLUGIN_NAME, expr => {
+ .tap(PLUGIN_NAME, (expr) => {
/** @type {BuildInfo} */
(parser.state.module.buildInfo).moduleConcatenationBailout =
RuntimeGlobals.moduleId;
diff --git a/lib/dependencies/ContextDependency.js b/lib/dependencies/ContextDependency.js
index e1d94b5ece7..bcec13d18d5 100644
--- a/lib/dependencies/ContextDependency.js
+++ b/lib/dependencies/ContextDependency.js
@@ -27,7 +27,7 @@ const getCriticalDependencyWarning = memoize(() =>
* @param {RegExp | null | undefined} r regexp
* @returns {string} stringified regexp
*/
-const regExpToString = r => (r ? String(r) : "");
+const regExpToString = (r) => (r ? String(r) : "");
class ContextDependency extends Dependency {
/**
diff --git a/lib/dependencies/ContextDependencyHelpers.js b/lib/dependencies/ContextDependencyHelpers.js
index 6f18e062ca8..a0e713bff3e 100644
--- a/lib/dependencies/ContextDependencyHelpers.js
+++ b/lib/dependencies/ContextDependencyHelpers.js
@@ -22,13 +22,13 @@ const { parseResource } = require("../util/identifier");
* @param {string} str String to quote
* @returns {string} Escaped string
*/
-const quoteMeta = str => str.replace(/[-[\]\\/{}()*+?.^$|]/g, "\\$&");
+const quoteMeta = (str) => str.replace(/[-[\]\\/{}()*+?.^$|]/g, "\\$&");
/**
* @param {string} prefix prefix
* @returns {{prefix: string, context: string}} result
*/
-const splitContextFromPrefix = prefix => {
+const splitContextFromPrefix = (prefix) => {
const idx = prefix.lastIndexOf("/");
let context = ".";
if (idx >= 0) {
@@ -87,7 +87,7 @@ module.exports.create = (
/** @type {RegExp} */ (options.wrappedContextRegExp).source +
innerQuasis
.map(
- q =>
+ (q) =>
quoteMeta(/** @type {string} */ (q.string)) +
/** @type {RegExp} */ (options.wrappedContextRegExp).source
)
diff --git a/lib/dependencies/CssIcssExportDependency.js b/lib/dependencies/CssIcssExportDependency.js
index 5b03b9ff6bb..a4bb379c91b 100644
--- a/lib/dependencies/CssIcssExportDependency.js
+++ b/lib/dependencies/CssIcssExportDependency.js
@@ -65,7 +65,7 @@ class CssIcssExportDependency extends NullDependency {
(generator.convention)
);
return {
- exports: names.map(name => ({
+ exports: names.map((name) => ({
name,
canMangle: true
})),
@@ -139,7 +139,7 @@ CssIcssExportDependency.Template = class CssIcssExportDependencyTemplate extends
/** @type {string[]} */
(
names
- .map(name =>
+ .map((name) =>
moduleGraph.getExportInfo(module, name).getUsedName(name, runtime)
)
.filter(Boolean)
diff --git a/lib/dependencies/CssLocalIdentifierDependency.js b/lib/dependencies/CssLocalIdentifierDependency.js
index 4592c45b1df..3be3ef0388f 100644
--- a/lib/dependencies/CssLocalIdentifierDependency.js
+++ b/lib/dependencies/CssLocalIdentifierDependency.js
@@ -127,7 +127,7 @@ class CssLocalIdentifierDependency extends NullDependency {
/** @type {CssGeneratorExportsConvention} */ (generator.convention)
);
return {
- exports: names.map(name => ({
+ exports: names.map((name) => ({
name,
canMangle: true
})),
@@ -225,7 +225,7 @@ CssLocalIdentifierDependency.Template = class CssLocalIdentifierDependencyTempla
/** @type {string[]} */
(
names
- .map(name =>
+ .map((name) =>
moduleGraph.getExportInfo(module, name).getUsedName(name, runtime)
)
.filter(Boolean)
diff --git a/lib/dependencies/CssUrlDependency.js b/lib/dependencies/CssUrlDependency.js
index ad3ec31feef..a7cb4349cd4 100644
--- a/lib/dependencies/CssUrlDependency.js
+++ b/lib/dependencies/CssUrlDependency.js
@@ -82,7 +82,7 @@ class CssUrlDependency extends ModuleDependency {
* @param {string} str string
* @returns {string} string in quotes if needed
*/
-const cssEscapeString = str => {
+const cssEscapeString = (str) => {
let countWhiteOrBracket = 0;
let countQuotation = 0;
let countApostrophe = 0;
@@ -105,11 +105,11 @@ const cssEscapeString = str => {
}
}
if (countWhiteOrBracket < 2) {
- return str.replace(/[\n\t ()'"\\]/g, m => `\\${m}`);
+ return str.replace(/[\n\t ()'"\\]/g, (m) => `\\${m}`);
} else if (countQuotation <= countApostrophe) {
- return `"${str.replace(/[\n"\\]/g, m => `\\${m}`)}"`;
+ return `"${str.replace(/[\n"\\]/g, (m) => `\\${m}`)}"`;
}
- return `'${str.replace(/[\n'\\]/g, m => `\\${m}`)}'`;
+ return `'${str.replace(/[\n'\\]/g, (m) => `\\${m}`)}'`;
};
CssUrlDependency.Template = class CssUrlDependencyTemplate extends (
diff --git a/lib/dependencies/DynamicExports.js b/lib/dependencies/DynamicExports.js
index 4e983ddbddb..1d97fa5a90c 100644
--- a/lib/dependencies/DynamicExports.js
+++ b/lib/dependencies/DynamicExports.js
@@ -15,7 +15,7 @@ const parserStateExportsState = new WeakMap();
* @param {ParserState} parserState parser state
* @returns {void}
*/
-module.exports.bailout = parserState => {
+module.exports.bailout = (parserState) => {
const value = parserStateExportsState.get(parserState);
parserStateExportsState.set(parserState, false);
if (value === true) {
@@ -29,7 +29,7 @@ module.exports.bailout = parserState => {
* @param {ParserState} parserState parser state
* @returns {void}
*/
-module.exports.enable = parserState => {
+module.exports.enable = (parserState) => {
const value = parserStateExportsState.get(parserState);
if (value === false) return;
parserStateExportsState.set(parserState, true);
@@ -44,7 +44,7 @@ module.exports.enable = parserState => {
* @param {ParserState} parserState parser state
* @returns {boolean} true, when enabled
*/
-module.exports.isEnabled = parserState => {
+module.exports.isEnabled = (parserState) => {
const value = parserStateExportsState.get(parserState);
return value === true;
};
@@ -53,7 +53,7 @@ module.exports.isEnabled = parserState => {
* @param {ParserState} parserState parser state
* @returns {void}
*/
-module.exports.setDynamic = parserState => {
+module.exports.setDynamic = (parserState) => {
const value = parserStateExportsState.get(parserState);
if (value !== true) return;
/** @type {BuildMeta} */
@@ -64,7 +64,7 @@ module.exports.setDynamic = parserState => {
* @param {ParserState} parserState parser state
* @returns {void}
*/
-module.exports.setFlagged = parserState => {
+module.exports.setFlagged = (parserState) => {
const value = parserStateExportsState.get(parserState);
if (value !== true) return;
const buildMeta = /** @type {BuildMeta} */ (parserState.module.buildMeta);
diff --git a/lib/dependencies/HarmonyAcceptDependency.js b/lib/dependencies/HarmonyAcceptDependency.js
index 4817b722d7e..d236d4f887c 100644
--- a/lib/dependencies/HarmonyAcceptDependency.js
+++ b/lib/dependencies/HarmonyAcceptDependency.js
@@ -6,6 +6,7 @@
"use strict";
const Template = require("../Template");
+const AwaitDependenciesInitFragment = require("../async-modules/AwaitDependenciesInitFragment");
const makeSerializable = require("../util/makeSerializable");
const HarmonyImportDependency = require("./HarmonyImportDependency");
const NullDependency = require("./NullDependency");
@@ -82,8 +83,25 @@ HarmonyAcceptDependency.Template = class HarmonyAcceptDependencyTemplate extends
moduleGraph,
chunkGraph
} = templateContext;
- const content = dep.dependencies
- .map(dependency => {
+
+ /** @type {HarmonyAcceptImportDependency[]} */
+ const syncDeps = [];
+
+ /** @type {HarmonyAcceptImportDependency[]} */
+ const asyncDeps = [];
+
+ for (const dependency of dep.dependencies) {
+ const connection = moduleGraph.getConnection(dependency);
+
+ if (connection && moduleGraph.isAsync(connection.module)) {
+ asyncDeps.push(dependency);
+ } else {
+ syncDeps.push(dependency);
+ }
+ }
+
+ let content = syncDeps
+ .map((dependency) => {
const referencedModule = moduleGraph.getModule(dependency);
return {
dependency,
@@ -112,17 +130,33 @@ HarmonyAcceptDependency.Template = class HarmonyAcceptDependencyTemplate extends
})
.join("");
+ const promises = new Map(
+ asyncDeps.map((dependency) => [
+ dependency.getImportVar(moduleGraph),
+ dependency.getModuleExports(templateContext)
+ ])
+ );
+
+ let optAsync = "";
+ if (promises.size !== 0) {
+ optAsync = "async ";
+ content += new AwaitDependenciesInitFragment(promises).getContent({
+ ...templateContext,
+ type: "javascript"
+ });
+ }
+
if (dep.hasCallback) {
if (runtimeTemplate.supportsArrowFunction()) {
source.insert(
dep.range[0],
- `__WEBPACK_OUTDATED_DEPENDENCIES__ => { ${content}(`
+ `${optAsync}__WEBPACK_OUTDATED_DEPENDENCIES__ => { ${content} return (`
);
source.insert(dep.range[1], ")(__WEBPACK_OUTDATED_DEPENDENCIES__); }");
} else {
source.insert(
dep.range[0],
- `function(__WEBPACK_OUTDATED_DEPENDENCIES__) { ${content}(`
+ `${optAsync}function(__WEBPACK_OUTDATED_DEPENDENCIES__) { ${content} return (`
);
source.insert(
dep.range[1],
@@ -135,7 +169,7 @@ HarmonyAcceptDependency.Template = class HarmonyAcceptDependencyTemplate extends
const arrow = runtimeTemplate.supportsArrowFunction();
source.insert(
dep.range[1] - 0.5,
- `, ${arrow ? "() =>" : "function()"} { ${content} }`
+ `, ${arrow ? `${optAsync}() =>` : `${optAsync}function()`} { ${content} }`
);
}
};
diff --git a/lib/dependencies/HarmonyDetectionParserPlugin.js b/lib/dependencies/HarmonyDetectionParserPlugin.js
index dcb2d145c20..7edd8dd5d59 100644
--- a/lib/dependencies/HarmonyDetectionParserPlugin.js
+++ b/lib/dependencies/HarmonyDetectionParserPlugin.js
@@ -31,13 +31,13 @@ module.exports = class HarmonyDetectionParserPlugin {
* @returns {void}
*/
apply(parser) {
- parser.hooks.program.tap(PLUGIN_NAME, ast => {
+ parser.hooks.program.tap(PLUGIN_NAME, (ast) => {
const isStrictHarmony =
parser.state.module.type === JAVASCRIPT_MODULE_TYPE_ESM;
const isHarmony =
isStrictHarmony ||
ast.body.some(
- statement =>
+ (statement) =>
statement.type === "ImportDeclaration" ||
statement.type === "ExportDefaultDeclaration" ||
statement.type === "ExportNamedDeclaration" ||
diff --git a/lib/dependencies/HarmonyExportDependencyParserPlugin.js b/lib/dependencies/HarmonyExportDependencyParserPlugin.js
index 4349b0b26f5..be2056fee9f 100644
--- a/lib/dependencies/HarmonyExportDependencyParserPlugin.js
+++ b/lib/dependencies/HarmonyExportDependencyParserPlugin.js
@@ -33,9 +33,8 @@ const PLUGIN_NAME = "HarmonyExportDependencyParserPlugin";
module.exports = class HarmonyExportDependencyParserPlugin {
/**
* @param {import("../../declarations/WebpackOptions").JavascriptParserOptions} options options
- * @param {boolean=} deferImport defer import enabled
*/
- constructor(options, deferImport) {
+ constructor(options) {
this.exportPresenceMode =
options.reexportExportsPresence !== undefined
? ExportPresenceModes.fromUserOption(options.reexportExportsPresence)
@@ -44,7 +43,7 @@ module.exports = class HarmonyExportDependencyParserPlugin {
: options.strictExportPresence
? ExportPresenceModes.ERROR
: ExportPresenceModes.AUTO;
- this.deferImport = deferImport;
+ this.deferImport = options.deferImport;
}
/**
@@ -53,7 +52,7 @@ module.exports = class HarmonyExportDependencyParserPlugin {
*/
apply(parser) {
const { exportPresenceMode } = this;
- parser.hooks.export.tap(PLUGIN_NAME, statement => {
+ parser.hooks.export.tap(PLUGIN_NAME, (statement) => {
const dep = new HarmonyExportHeaderDependency(
/** @type {Range | false} */ (
statement.declaration && statement.declaration.range
@@ -77,13 +76,16 @@ module.exports = class HarmonyExportDependencyParserPlugin {
clearDep.loc = /** @type {DependencyLocation} */ (statement.loc);
clearDep.loc.index = -1;
parser.state.module.addPresentationalDependency(clearDep);
- const { defer } = getImportMode(parser, statement);
- if (defer) {
- const error = new WebpackError(
- "Deferred re-export (`export defer * as namespace from '...'`) is not a part of the Import Defer proposal.\nUse the following code instead:\n import defer * as namespace from '...';\n export { namespace };"
- );
- error.loc = statement.loc || undefined;
- parser.state.current.addError(error);
+ let defer = false;
+ if (this.deferImport) {
+ ({ defer } = getImportMode(parser, statement));
+ if (defer) {
+ const error = new WebpackError(
+ "Deferred re-export (`export defer * as namespace from '...'`) is not a part of the Import Defer proposal.\nUse the following code instead:\n import defer * as namespace from '...';\n export { namespace };"
+ );
+ error.loc = statement.loc || undefined;
+ parser.state.current.addError(error);
+ }
}
const sideEffectDep = new HarmonyImportSideEffectDependency(
/** @type {string} */ (source),
@@ -107,7 +109,7 @@ module.exports = class HarmonyExportDependencyParserPlugin {
exprRange,
statementRange,
comments
- .map(c => {
+ .map((c) => {
switch (c.type) {
case "Block":
return `/*${c.value}*/`;
@@ -202,7 +204,9 @@ module.exports = class HarmonyExportDependencyParserPlugin {
parser.state.harmonyStarExports || new HarmonyStarExportsList();
}
const attributes = getImportAttributes(statement);
- const { defer } = getImportMode(parser, statement);
+ const defer = this.deferImport
+ ? getImportMode(parser, statement).defer
+ : false;
const dep = new HarmonyExportImportedSpecifierDependency(
/** @type {string} */
(source),
diff --git a/lib/dependencies/HarmonyExportImportedSpecifierDependency.js b/lib/dependencies/HarmonyExportImportedSpecifierDependency.js
index 07fad95ccd4..84eabafe3f4 100644
--- a/lib/dependencies/HarmonyExportImportedSpecifierDependency.js
+++ b/lib/dependencies/HarmonyExportImportedSpecifierDependency.js
@@ -334,7 +334,7 @@ const getMode = (moduleGraph, dep, runtimeKey) => {
mode.items = Array.from(
exports,
- exportName =>
+ (exportName) =>
new NormalReexportItem(
exportName,
[exportName],
@@ -378,7 +378,7 @@ class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency {
* @param {ExportPresenceMode} exportPresenceMode mode of checking export names
* @param {HarmonyStarExportsList | null} allStarExports all star exports in the module
* @param {ImportAttributes=} attributes import attributes
- * @param {boolean=} deferEvaluation defer evaluation
+ * @param {boolean=} defer is defer phase
*/
constructor(
request,
@@ -390,9 +390,9 @@ class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency {
exportPresenceMode,
allStarExports,
attributes,
- deferEvaluation
+ defer
) {
- super(request, sourceOrder, attributes);
+ super(request, sourceOrder, attributes, defer);
this.ids = ids;
this.name = name;
@@ -400,7 +400,6 @@ class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency {
this.otherStarExports = otherStarExports;
this.exportPresenceMode = exportPresenceMode;
this.allStarExports = allStarExports;
- this.defer = deferEvaluation;
}
/**
@@ -722,7 +721,7 @@ class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency {
return {
exports: Array.from(
/** @type {NormalReexportItem[]} */ (mode.items),
- item => ({
+ (item) => ({
name: item.name,
from,
export: item.ids,
@@ -930,7 +929,7 @@ class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency {
}' contains conflicting star exports for the ${
exports.length > 1 ? "names" : "name"
} ${exports
- .map(e => `'${e}'`)
+ .map((e) => `'${e}'`)
.join(", ")} with the previous requested module '${request}'`
)
);
@@ -1190,7 +1189,7 @@ HarmonyExportImportedSpecifierDependency.Template = class HarmonyExportImportedS
const runtimeCondition = dep.weak
? false
: connection
- ? filterRuntime(runtime, r => connection.isTargetActive(r))
+ ? filterRuntime(runtime, (r) => connection.isTargetActive(r))
: true;
initFragments.push(
new ConditionalInitFragment(
diff --git a/lib/dependencies/HarmonyExportInitFragment.js b/lib/dependencies/HarmonyExportInitFragment.js
index 9b4b025c145..d81cbad9227 100644
--- a/lib/dependencies/HarmonyExportInitFragment.js
+++ b/lib/dependencies/HarmonyExportInitFragment.js
@@ -17,7 +17,7 @@ const { propertyName } = require("../util/propertyName");
* @param {Iterable} iterable iterable strings
* @returns {string} result
*/
-const joinIterableWithComma = iterable => {
+const joinIterableWithComma = (iterable) => {
// This is more performant than Array.from().join(", ")
// as it doesn't create an array
let str = "";
diff --git a/lib/dependencies/HarmonyExports.js b/lib/dependencies/HarmonyExports.js
index 1f6e6d4acb9..fe1b28d4e36 100644
--- a/lib/dependencies/HarmonyExports.js
+++ b/lib/dependencies/HarmonyExports.js
@@ -40,7 +40,7 @@ module.exports.enable = (parserState, isStrictHarmony) => {
* @param {ParserState} parserState parser state
* @returns {boolean} true, when enabled
*/
-module.exports.isEnabled = parserState => {
+module.exports.isEnabled = (parserState) => {
const value = parserStateExportsState.get(parserState);
return value === true;
};
diff --git a/lib/dependencies/HarmonyImportDependency.js b/lib/dependencies/HarmonyImportDependency.js
index 4ac805c8031..71bc6973572 100644
--- a/lib/dependencies/HarmonyImportDependency.js
+++ b/lib/dependencies/HarmonyImportDependency.js
@@ -64,11 +64,13 @@ class HarmonyImportDependency extends ModuleDependency {
* @param {string} request request string
* @param {number} sourceOrder source order
* @param {ImportAttributes=} attributes import attributes
+ * @param {boolean=} defer import attributes
*/
- constructor(request, sourceOrder, attributes) {
+ constructor(request, sourceOrder, attributes, defer) {
super(request);
this.sourceOrder = sourceOrder;
this.assertions = attributes;
+ this.defer = defer;
}
get category() {
@@ -112,6 +114,24 @@ class HarmonyImportDependency extends ModuleDependency {
return importVar;
}
+ /**
+ * @param {DependencyTemplateContext} context the template context
+ * @returns {string} the expression
+ */
+ getModuleExports({
+ runtimeTemplate,
+ moduleGraph,
+ chunkGraph,
+ runtimeRequirements
+ }) {
+ return runtimeTemplate.moduleExports({
+ module: moduleGraph.getModule(this),
+ chunkGraph,
+ request: this.request,
+ runtimeRequirements
+ });
+ }
+
/**
* @param {boolean} update create new variables or update existing one
* @param {DependencyTemplateContext} templateContext the template context
@@ -183,7 +203,7 @@ class HarmonyImportDependency extends ModuleDependency {
new HarmonyLinkingError(
`export ${ids
.slice(0, pos)
- .map(id => `'${id}'`)
+ .map((id) => `'${id}'`)
.join(".")} ${additionalMessage} was not found in '${
this.userRequest
}'${moreInfo}`
@@ -199,7 +219,7 @@ class HarmonyImportDependency extends ModuleDependency {
return [
new HarmonyLinkingError(
`export ${ids
- .map(id => `'${id}'`)
+ .map((id) => `'${id}'`)
.join(".")} ${additionalMessage} was not found in '${
this.userRequest
}'`
@@ -215,7 +235,7 @@ class HarmonyImportDependency extends ModuleDependency {
return [
new HarmonyLinkingError(
`Can't import the named export ${ids
- .map(id => `'${id}'`)
+ .map((id) => `'${id}'`)
.join(
"."
)} ${additionalMessage} from default-exporting module (only default export is available)`
@@ -236,7 +256,7 @@ class HarmonyImportDependency extends ModuleDependency {
return [
new HarmonyLinkingError(
`Should not import the named export ${ids
- .map(id => `'${id}'`)
+ .map((id) => `'${id}'`)
.join(
"."
)} ${additionalMessage} from default-exporting module (only default export is available soon)`
@@ -310,7 +330,7 @@ HarmonyImportDependency.Template = class HarmonyImportDependencyTemplate extends
const runtimeCondition = dep.weak
? false
: connection
- ? filterRuntime(runtime, r => connection.isTargetActive(r))
+ ? filterRuntime(runtime, (r) => connection.isTargetActive(r))
: true;
if (module && referencedModule) {
@@ -348,10 +368,9 @@ HarmonyImportDependency.Template = class HarmonyImportDependencyTemplate extends
runtimeCondition
)
);
+ const importVar = dep.getImportVar(templateContext.moduleGraph);
templateContext.initFragments.push(
- new AwaitDependenciesInitFragment(
- new Set([dep.getImportVar(templateContext.moduleGraph)])
- )
+ new AwaitDependenciesInitFragment(new Map([[importVar, importVar]]))
);
templateContext.initFragments.push(
new ConditionalInitFragment(
diff --git a/lib/dependencies/HarmonyImportDependencyParserPlugin.js b/lib/dependencies/HarmonyImportDependencyParserPlugin.js
index 007c4261f7a..a54a4542c07 100644
--- a/lib/dependencies/HarmonyImportDependencyParserPlugin.js
+++ b/lib/dependencies/HarmonyImportDependencyParserPlugin.js
@@ -59,9 +59,8 @@ const PLUGIN_NAME = "HarmonyImportDependencyParserPlugin";
module.exports = class HarmonyImportDependencyParserPlugin {
/**
* @param {JavascriptParserOptions} options options
- * @param {boolean | undefined} deferImport defer import enabled
*/
- constructor(options, deferImport) {
+ constructor(options) {
this.exportPresenceMode =
options.importExportsPresence !== undefined
? ExportPresenceModes.fromUserOption(options.importExportsPresence)
@@ -71,7 +70,7 @@ module.exports = class HarmonyImportDependencyParserPlugin {
? ExportPresenceModes.ERROR
: ExportPresenceModes.AUTO;
this.strictThisContextOnImports = options.strictThisContextOnImports;
- this.deferImport = deferImport;
+ this.deferImport = options.deferImport;
}
/**
@@ -102,7 +101,7 @@ module.exports = class HarmonyImportDependencyParserPlugin {
return node;
}
- parser.hooks.isPure.for("Identifier").tap(PLUGIN_NAME, expression => {
+ parser.hooks.isPure.for("Identifier").tap(PLUGIN_NAME, (expression) => {
const expr = /** @type {Identifier} */ (expression);
if (
parser.isVariableDefined(expr.name) ||
@@ -124,17 +123,20 @@ module.exports = class HarmonyImportDependencyParserPlugin {
parser.state.module.addPresentationalDependency(clearDep);
parser.unsetAsiPosition(/** @type {Range} */ (statement.range)[1]);
const attributes = getImportAttributes(statement);
- const { defer } = getImportMode(parser, statement);
- if (
- defer &&
- (statement.specifiers.length !== 1 ||
- statement.specifiers[0].type !== "ImportNamespaceSpecifier")
- ) {
- const error = new WebpackError(
- "Deferred import can only be used with `import * as namespace from '...'` syntax."
- );
- error.loc = statement.loc || undefined;
- parser.state.current.addError(error);
+ let defer = false;
+ if (this.deferImport) {
+ ({ defer } = getImportMode(parser, statement));
+ if (
+ defer &&
+ (statement.specifiers.length !== 1 ||
+ statement.specifiers[0].type !== "ImportNamespaceSpecifier")
+ ) {
+ const error = new WebpackError(
+ "Deferred import can only be used with `import * as namespace from '...'` syntax."
+ );
+ error.loc = statement.loc || undefined;
+ parser.state.current.addError(error);
+ }
}
const sideEffectDep = new HarmonyImportSideEffectDependency(
/** @type {string} */ (source),
@@ -150,7 +152,9 @@ module.exports = class HarmonyImportDependencyParserPlugin {
PLUGIN_NAME,
(statement, source, id, name) => {
const ids = id === null ? [] : [id];
- const { defer } = getImportMode(parser, statement);
+ const defer = this.deferImport
+ ? getImportMode(parser, statement).defer
+ : false;
parser.tagVariable(name, harmonySpecifierTag, {
name,
source,
@@ -162,7 +166,7 @@ module.exports = class HarmonyImportDependencyParserPlugin {
return true;
}
);
- parser.hooks.binaryExpression.tap(PLUGIN_NAME, expression => {
+ parser.hooks.binaryExpression.tap(PLUGIN_NAME, (expression) => {
if (expression.operator !== "in") return;
const leftPartEvaluated = parser.evaluateExpression(expression.left);
@@ -204,34 +208,38 @@ module.exports = class HarmonyImportDependencyParserPlugin {
);
dep.loc = /** @type {DependencyLocation} */ (expression.loc);
parser.state.module.addDependency(dep);
- InnerGraph.onUsage(parser.state, e => (dep.usedByExports = e));
- return true;
- });
- parser.hooks.expression.for(harmonySpecifierTag).tap(PLUGIN_NAME, expr => {
- const settings = /** @type {HarmonySettings} */ (parser.currentTagData);
- const dep = new HarmonyImportSpecifierDependency(
- settings.source,
- settings.sourceOrder,
- settings.ids,
- settings.name,
- /** @type {Range} */
- (expr.range),
- exportPresenceMode,
- settings.attributes,
- [],
- settings.defer
- );
- dep.referencedPropertiesInDestructuring =
- parser.destructuringAssignmentPropertiesFor(expr);
- dep.shorthand = parser.scope.inShorthand;
- dep.directImport = true;
- dep.asiSafe = !parser.isAsiPosition(/** @type {Range} */ (expr.range)[0]);
- dep.loc = /** @type {DependencyLocation} */ (expr.loc);
- dep.call = parser.scope.inTaggedTemplateTag;
- parser.state.module.addDependency(dep);
- InnerGraph.onUsage(parser.state, e => (dep.usedByExports = e));
+ InnerGraph.onUsage(parser.state, (e) => (dep.usedByExports = e));
return true;
});
+ parser.hooks.expression
+ .for(harmonySpecifierTag)
+ .tap(PLUGIN_NAME, (expr) => {
+ const settings = /** @type {HarmonySettings} */ (parser.currentTagData);
+ const dep = new HarmonyImportSpecifierDependency(
+ settings.source,
+ settings.sourceOrder,
+ settings.ids,
+ settings.name,
+ /** @type {Range} */
+ (expr.range),
+ exportPresenceMode,
+ settings.attributes,
+ [],
+ settings.defer
+ );
+ dep.referencedPropertiesInDestructuring =
+ parser.destructuringAssignmentPropertiesFor(expr);
+ dep.shorthand = parser.scope.inShorthand;
+ dep.directImport = true;
+ dep.asiSafe = !parser.isAsiPosition(
+ /** @type {Range} */ (expr.range)[0]
+ );
+ dep.loc = /** @type {DependencyLocation} */ (expr.loc);
+ dep.call = parser.scope.inTaggedTemplateTag;
+ parser.state.module.addDependency(dep);
+ InnerGraph.onUsage(parser.state, (e) => (dep.usedByExports = e));
+ return true;
+ });
parser.hooks.expressionMemberChain
.for(harmonySpecifierTag)
.tap(
@@ -277,7 +285,7 @@ module.exports = class HarmonyImportDependencyParserPlugin {
);
dep.loc = /** @type {DependencyLocation} */ (expr.loc);
parser.state.module.addDependency(dep);
- InnerGraph.onUsage(parser.state, e => (dep.usedByExports = e));
+ InnerGraph.onUsage(parser.state, (e) => (dep.usedByExports = e));
return true;
}
);
@@ -331,7 +339,7 @@ module.exports = class HarmonyImportDependencyParserPlugin {
dep.loc = /** @type {DependencyLocation} */ (expr.loc);
parser.state.module.addDependency(dep);
if (args) parser.walkExpressions(args);
- InnerGraph.onUsage(parser.state, e => (dep.usedByExports = e));
+ InnerGraph.onUsage(parser.state, (e) => (dep.usedByExports = e));
return true;
}
);
@@ -342,7 +350,7 @@ module.exports = class HarmonyImportDependencyParserPlugin {
// This is not a harmony module, skip it
return;
}
- const dependencies = requests.map(request => {
+ const dependencies = requests.map((request) => {
const dep = new HarmonyAcceptImportDependency(request);
dep.loc = /** @type {DependencyLocation} */ (expr.loc);
parser.state.module.addDependency(dep);
@@ -364,7 +372,7 @@ module.exports = class HarmonyImportDependencyParserPlugin {
// This is not a harmony module, skip it
return;
}
- const dependencies = requests.map(request => {
+ const dependencies = requests.map((request) => {
const dep = new HarmonyAcceptImportDependency(request);
dep.loc = /** @type {DependencyLocation} */ (expr.loc);
parser.state.module.addDependency(dep);
@@ -387,7 +395,7 @@ module.exports = class HarmonyImportDependencyParserPlugin {
/**
* @param {JavascriptParser} parser parser
* @param {ExportNamedDeclaration | ExportAllDeclaration | ImportDeclaration} node node
- * @returns {{defer: boolean}} import attributes
+ * @returns {{ defer: boolean }} import attributes
*/
function getImportMode(parser, node) {
const result = { defer: "phase" in node && node.phase === "defer" };
diff --git a/lib/dependencies/HarmonyImportSideEffectDependency.js b/lib/dependencies/HarmonyImportSideEffectDependency.js
index 5911c5b3386..9db49f07ddb 100644
--- a/lib/dependencies/HarmonyImportSideEffectDependency.js
+++ b/lib/dependencies/HarmonyImportSideEffectDependency.js
@@ -26,11 +26,10 @@ class HarmonyImportSideEffectDependency extends HarmonyImportDependency {
* @param {string} request the request string
* @param {number} sourceOrder source order
* @param {ImportAttributes=} attributes import attributes
- * @param {boolean=} deferred deferred
+ * @param {boolean=} defer is defer phase
*/
- constructor(request, sourceOrder, attributes, deferred) {
- super(request, sourceOrder, attributes);
- this.defer = deferred;
+ constructor(request, sourceOrder, attributes, defer) {
+ super(request, sourceOrder, attributes, defer);
}
get type() {
@@ -42,7 +41,7 @@ class HarmonyImportSideEffectDependency extends HarmonyImportDependency {
* @returns {null | false | GetConditionFn} function to determine if the connection is active
*/
getCondition(moduleGraph) {
- return connection => {
+ return (connection) => {
const refModule = connection.resolvedModule;
if (!refModule) return true;
return refModule.getSideEffectsConnectionState(moduleGraph);
diff --git a/lib/dependencies/HarmonyImportSpecifierDependency.js b/lib/dependencies/HarmonyImportSpecifierDependency.js
index a6d0c140de2..bf3f7070d40 100644
--- a/lib/dependencies/HarmonyImportSpecifierDependency.js
+++ b/lib/dependencies/HarmonyImportSpecifierDependency.js
@@ -51,7 +51,7 @@ class HarmonyImportSpecifierDependency extends HarmonyImportDependency {
* @param {ExportPresenceMode} exportPresenceMode export presence mode
* @param {ImportAttributes | undefined} attributes import attributes
* @param {Range[] | undefined} idRanges ranges for members of ids; the two arrays are right-aligned
- * @param {boolean=} deferred deferred
+ * @param {boolean=} defer is defer phase
*/
constructor(
request,
@@ -62,9 +62,9 @@ class HarmonyImportSpecifierDependency extends HarmonyImportDependency {
exportPresenceMode,
attributes,
idRanges, // TODO webpack 6 make this non-optional. It must always be set to properly trim ids.
- deferred
+ defer
) {
- super(request, sourceOrder, attributes);
+ super(request, sourceOrder, attributes, defer);
this.ids = ids;
this.name = name;
this.range = range;
@@ -79,7 +79,6 @@ class HarmonyImportSpecifierDependency extends HarmonyImportDependency {
this.usedByExports = undefined;
/** @type {Set | undefined} */
this.referencedPropertiesInDestructuring = undefined;
- this.defer = deferred;
}
// TODO webpack 6 remove
diff --git a/lib/dependencies/HarmonyModulesPlugin.js b/lib/dependencies/HarmonyModulesPlugin.js
index 77d3d9c3dc9..3d2bf7230a0 100644
--- a/lib/dependencies/HarmonyModulesPlugin.js
+++ b/lib/dependencies/HarmonyModulesPlugin.js
@@ -135,14 +135,8 @@ class HarmonyModulesPlugin {
}
new HarmonyDetectionParserPlugin(this.options).apply(parser);
- new HarmonyImportDependencyParserPlugin(
- parserOptions,
- this.options.deferImport
- ).apply(parser);
- new HarmonyExportDependencyParserPlugin(
- parserOptions,
- this.options.deferImport
- ).apply(parser);
+ new HarmonyImportDependencyParserPlugin(parserOptions).apply(parser);
+ new HarmonyExportDependencyParserPlugin(parserOptions).apply(parser);
new HarmonyTopLevelThisParserPlugin().apply(parser);
};
diff --git a/lib/dependencies/HarmonyTopLevelThisParserPlugin.js b/lib/dependencies/HarmonyTopLevelThisParserPlugin.js
index c8a3061a0be..5039eb9da7f 100644
--- a/lib/dependencies/HarmonyTopLevelThisParserPlugin.js
+++ b/lib/dependencies/HarmonyTopLevelThisParserPlugin.js
@@ -20,7 +20,7 @@ class HarmonyTopLevelThisParserPlugin {
* @returns {void}
*/
apply(parser) {
- parser.hooks.expression.for("this").tap(PLUGIN_NAME, node => {
+ parser.hooks.expression.for("this").tap(PLUGIN_NAME, (node) => {
if (!parser.scope.topLevelScope) return;
if (HarmonyExports.isEnabled(parser.state)) {
const dep = new ConstDependency(
diff --git a/lib/dependencies/ImportMetaContextDependencyParserPlugin.js b/lib/dependencies/ImportMetaContextDependencyParserPlugin.js
index 6b5c2bb6aaa..d52c09d5ccf 100644
--- a/lib/dependencies/ImportMetaContextDependencyParserPlugin.js
+++ b/lib/dependencies/ImportMetaContextDependencyParserPlugin.js
@@ -62,7 +62,7 @@ module.exports = class ImportMetaContextDependencyParserPlugin {
apply(parser) {
parser.hooks.evaluateIdentifier
.for("import.meta.webpackContext")
- .tap(PLUGIN_NAME, expr =>
+ .tap(PLUGIN_NAME, (expr) =>
evaluateToIdentifier(
"import.meta.webpackContext",
"import.meta",
@@ -72,7 +72,7 @@ module.exports = class ImportMetaContextDependencyParserPlugin {
);
parser.hooks.call
.for("import.meta.webpackContext")
- .tap(PLUGIN_NAME, expr => {
+ .tap(PLUGIN_NAME, (expr) => {
if (expr.arguments.length < 1 || expr.arguments.length > 2) return;
const [directoryNode, optionsNode] = expr.arguments;
if (optionsNode && optionsNode.type !== "ObjectExpression") return;
@@ -178,11 +178,11 @@ module.exports = class ImportMetaContextDependencyParserPlugin {
/** @type {BasicEvaluatedExpression[]} */
(expr.items);
if (
- items.every(i => {
+ items.every((i) => {
if (!i.isArray()) return false;
const innerItems =
/** @type {BasicEvaluatedExpression[]} */ (i.items);
- return innerItems.every(i => i.isString());
+ return innerItems.every((i) => i.isString());
})
) {
exports = [];
diff --git a/lib/dependencies/ImportMetaPlugin.js b/lib/dependencies/ImportMetaPlugin.js
index 779f44b921f..17817f7de21 100644
--- a/lib/dependencies/ImportMetaPlugin.js
+++ b/lib/dependencies/ImportMetaPlugin.js
@@ -49,7 +49,7 @@ class ImportMetaPlugin {
* @param {NormalModule} module module
* @returns {string} file url
*/
- const getUrl = module => pathToFileURL(module.resource).toString();
+ const getUrl = (module) => pathToFileURL(module.resource).toString();
/**
* @param {Parser} parser parser parser
* @param {JavascriptParserOptions} parserOptions parserOptions
@@ -62,7 +62,7 @@ class ImportMetaPlugin {
parser.hooks.expression
.for("import.meta")
- .tap(PLUGIN_NAME, metaProperty => {
+ .tap(PLUGIN_NAME, (metaProperty) => {
const dep = new ConstDependency(
/** @type {string} */ (importMetaName),
/** @type {Range} */ (metaProperty.range)
@@ -86,7 +86,7 @@ class ImportMetaPlugin {
* @param {string[]} members members
* @returns {string} error message
*/
- const importMetaUnknownProperty = members =>
+ const importMetaUnknownProperty = (members) =>
`${Template.toNormalComment(
`unsupported import.meta.${members.join(".")}`
)} undefined${propertyAccess(members, 1)}`;
@@ -98,7 +98,7 @@ class ImportMetaPlugin {
);
parser.hooks.expression
.for("import.meta")
- .tap(PLUGIN_NAME, metaProperty => {
+ .tap(PLUGIN_NAME, (metaProperty) => {
const referencedPropertiesInDestructuring =
parser.destructuringAssignmentPropertiesFor(metaProperty);
if (!referencedPropertiesInDestructuring) {
@@ -169,7 +169,7 @@ class ImportMetaPlugin {
);
parser.hooks.expression
.for("import.meta.url")
- .tap(PLUGIN_NAME, expr => {
+ .tap(PLUGIN_NAME, (expr) => {
const dep = new ConstDependency(
importMetaUrl(),
/** @type {Range} */ (expr.range)
@@ -183,7 +183,7 @@ class ImportMetaPlugin {
.tap(PLUGIN_NAME, evaluateToString("string"));
parser.hooks.evaluateIdentifier
.for("import.meta.url")
- .tap(PLUGIN_NAME, expr =>
+ .tap(PLUGIN_NAME, (expr) =>
new BasicEvaluatedExpression()
.setString(getUrl(parser.state.module))
.setRange(/** @type {Range} */ (expr.range))
@@ -223,7 +223,7 @@ class ImportMetaPlugin {
});
parser.hooks.evaluate
.for("MemberExpression")
- .tap(PLUGIN_NAME, expression => {
+ .tap(PLUGIN_NAME, (expression) => {
const expr = /** @type {MemberExpression} */ (expression);
if (
expr.object.type === "MetaProperty" &&
diff --git a/lib/dependencies/ImportParserPlugin.js b/lib/dependencies/ImportParserPlugin.js
index b41e43dd683..8ad5da34b24 100644
--- a/lib/dependencies/ImportParserPlugin.js
+++ b/lib/dependencies/ImportParserPlugin.js
@@ -44,9 +44,9 @@ class ImportParserPlugin {
* @param {Iterable} enumerable enumerable
* @returns {T[][]} array of array
*/
- const exportsFromEnumerable = enumerable =>
- Array.from(enumerable, e => [e]);
- parser.hooks.importCall.tap(PLUGIN_NAME, expr => {
+ const exportsFromEnumerable = (enumerable) =>
+ Array.from(enumerable, (e) => [e]);
+ parser.hooks.importCall.tap(PLUGIN_NAME, (expr) => {
const param = parser.evaluateExpression(expr.source);
let chunkName = null;
@@ -240,7 +240,7 @@ class ImportParserPlugin {
typeof importOptions.webpackExports === "string" ||
(Array.isArray(importOptions.webpackExports) &&
/** @type {string[]} */ (importOptions.webpackExports).every(
- item => typeof item === "string"
+ (item) => typeof item === "string"
))
)
) {
diff --git a/lib/dependencies/JsonExportsDependency.js b/lib/dependencies/JsonExportsDependency.js
index 08e062ab300..b283eb7419f 100644
--- a/lib/dependencies/JsonExportsDependency.js
+++ b/lib/dependencies/JsonExportsDependency.js
@@ -30,7 +30,7 @@ const NullDependency = require("./NullDependency");
* @param {number} exportsDepth exportsDepth
* @returns {GetExportsFromDataFn} value
*/
-const getExportsWithDepth = exportsDepth =>
+const getExportsWithDepth = (exportsDepth) =>
/** @type {GetExportsFromDataFn} */
function getExportsFromData(data, curDepth = 1) {
if (curDepth > exportsDepth) {
diff --git a/lib/dependencies/LoaderPlugin.js b/lib/dependencies/LoaderPlugin.js
index b61bfa303e1..c57250eae5d 100644
--- a/lib/dependencies/LoaderPlugin.js
+++ b/lib/dependencies/LoaderPlugin.js
@@ -54,11 +54,11 @@ class LoaderPlugin {
}
);
- compiler.hooks.compilation.tap(PLUGIN_NAME, compilation => {
+ compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
const moduleGraph = compilation.moduleGraph;
NormalModule.getCompilationHooks(compilation).loader.tap(
PLUGIN_NAME,
- loaderContext => {
+ (loaderContext) => {
loaderContext.loadModule = (request, callback) => {
const dep = new LoaderDependency(request);
dep.loc = {
@@ -91,7 +91,7 @@ class LoaderPlugin {
context: loaderContext.context,
recursive: false
},
- err => {
+ (err) => {
compilation.factorizeQueue.setContext(oldFactorizeQueueContext);
compilation.addModuleQueue.setContext(oldAddModuleQueueContext);
compilation.buildQueue.decreaseParallelism();
@@ -196,7 +196,7 @@ class LoaderPlugin {
connectOrigin: false,
checkCycle: true
},
- err => {
+ (err) => {
compilation.factorizeQueue.setContext(oldFactorizeQueueContext);
compilation.addModuleQueue.setContext(oldAddModuleQueueContext);
compilation.buildQueue.decreaseParallelism();
diff --git a/lib/dependencies/ProvidedDependency.js b/lib/dependencies/ProvidedDependency.js
index 9f1d3f6e7dc..422e1b63d65 100644
--- a/lib/dependencies/ProvidedDependency.js
+++ b/lib/dependencies/ProvidedDependency.js
@@ -29,9 +29,9 @@ const ModuleDependency = require("./ModuleDependency");
* @param {string[]|null} path the property path array
* @returns {string} the converted path
*/
-const pathToString = path =>
+const pathToString = (path) =>
path !== null && path.length > 0
- ? path.map(part => `[${JSON.stringify(part)}]`).join("")
+ ? path.map((part) => `[${JSON.stringify(part)}]`).join("")
: "";
class ProvidedDependency extends ModuleDependency {
diff --git a/lib/dependencies/PureExpressionDependency.js b/lib/dependencies/PureExpressionDependency.js
index 3c4312c9847..1df2517db1a 100644
--- a/lib/dependencies/PureExpressionDependency.js
+++ b/lib/dependencies/PureExpressionDependency.js
@@ -47,7 +47,7 @@ class PureExpressionDependency extends NullDependency {
/** @type {Module} */
(moduleGraph.getParentModule(this));
const exportsInfo = moduleGraph.getExportsInfo(selfModule);
- const runtimeCondition = filterRuntime(runtime, runtime => {
+ const runtimeCondition = filterRuntime(runtime, (runtime) => {
for (const exportName of usedByExports) {
if (exportsInfo.getUsed(exportName, runtime) !== UsageState.Unused) {
return true;
diff --git a/lib/dependencies/RequireContextDependencyParserPlugin.js b/lib/dependencies/RequireContextDependencyParserPlugin.js
index 9f794ba6dbc..08ac21631d8 100644
--- a/lib/dependencies/RequireContextDependencyParserPlugin.js
+++ b/lib/dependencies/RequireContextDependencyParserPlugin.js
@@ -20,7 +20,7 @@ module.exports = class RequireContextDependencyParserPlugin {
* @returns {void}
*/
apply(parser) {
- parser.hooks.call.for("require.context").tap(PLUGIN_NAME, expr => {
+ parser.hooks.call.for("require.context").tap(PLUGIN_NAME, (expr) => {
let regExp = /^\.\/.*$/;
let recursive = true;
/** @type {ContextMode} */
diff --git a/lib/dependencies/RequireEnsureDependenciesBlockParserPlugin.js b/lib/dependencies/RequireEnsureDependenciesBlockParserPlugin.js
index 9f9bc0c0ac1..9c9a9c68699 100644
--- a/lib/dependencies/RequireEnsureDependenciesBlockParserPlugin.js
+++ b/lib/dependencies/RequireEnsureDependenciesBlockParserPlugin.js
@@ -25,7 +25,7 @@ module.exports = class RequireEnsureDependenciesBlockParserPlugin {
* @returns {void}
*/
apply(parser) {
- parser.hooks.call.for("require.ensure").tap(PLUGIN_NAME, expr => {
+ parser.hooks.call.for("require.ensure").tap(PLUGIN_NAME, (expr) => {
/** @type {string | GroupOptions | null} */
let chunkName = null;
let errorExpressionArg = null;
diff --git a/lib/dependencies/RequireIncludeDependencyParserPlugin.js b/lib/dependencies/RequireIncludeDependencyParserPlugin.js
index ede50250dff..d6f59bf7222 100644
--- a/lib/dependencies/RequireIncludeDependencyParserPlugin.js
+++ b/lib/dependencies/RequireIncludeDependencyParserPlugin.js
@@ -33,7 +33,7 @@ module.exports = class RequireIncludeDependencyParserPlugin {
*/
apply(parser) {
const { warn } = this;
- parser.hooks.call.for("require.include").tap(PLUGIN_NAME, expr => {
+ parser.hooks.call.for("require.include").tap(PLUGIN_NAME, (expr) => {
if (expr.arguments.length !== 1) return;
const param = parser.evaluateExpression(expr.arguments[0]);
if (!param.isString()) return;
@@ -57,7 +57,7 @@ module.exports = class RequireIncludeDependencyParserPlugin {
});
parser.hooks.evaluateTypeof
.for("require.include")
- .tap(PLUGIN_NAME, expr => {
+ .tap(PLUGIN_NAME, (expr) => {
if (warn) {
parser.state.module.addWarning(
new RequireIncludeDeprecationWarning(
@@ -67,7 +67,7 @@ module.exports = class RequireIncludeDependencyParserPlugin {
}
return evaluateToString("function")(expr);
});
- parser.hooks.typeof.for("require.include").tap(PLUGIN_NAME, expr => {
+ parser.hooks.typeof.for("require.include").tap(PLUGIN_NAME, (expr) => {
if (warn) {
parser.state.module.addWarning(
new RequireIncludeDeprecationWarning(
diff --git a/lib/dependencies/SystemPlugin.js b/lib/dependencies/SystemPlugin.js
index b0e09fd1bc0..bd0ca25585b 100644
--- a/lib/dependencies/SystemPlugin.js
+++ b/lib/dependencies/SystemPlugin.js
@@ -63,7 +63,7 @@ class SystemPlugin {
/**
* @param {string} name name
*/
- const setNotSupported = name => {
+ const setNotSupported = (name) => {
parser.hooks.evaluateTypeof
.for(name)
.tap(PLUGIN_NAME, evaluateToString("undefined"));
@@ -101,7 +101,7 @@ class SystemPlugin {
setNotSupported("System.get");
setNotSupported("System.register");
- parser.hooks.expression.for("System").tap(PLUGIN_NAME, expr => {
+ parser.hooks.expression.for("System").tap(PLUGIN_NAME, (expr) => {
const dep = new ConstDependency(
RuntimeGlobals.system,
/** @type {Range} */ (expr.range),
@@ -112,7 +112,7 @@ class SystemPlugin {
return true;
});
- parser.hooks.call.for("System.import").tap(PLUGIN_NAME, expr => {
+ parser.hooks.call.for("System.import").tap(PLUGIN_NAME, (expr) => {
parser.state.module.addWarning(
new SystemImportDeprecationWarning(
/** @type {DependencyLocation} */ (expr.loc)
diff --git a/lib/dependencies/WorkerPlugin.js b/lib/dependencies/WorkerPlugin.js
index 8aea2db264d..6d28cfbe0ba 100644
--- a/lib/dependencies/WorkerPlugin.js
+++ b/lib/dependencies/WorkerPlugin.js
@@ -54,7 +54,7 @@ const WorkerDependency = require("./WorkerDependency");
* @param {NormalModule} module module
* @returns {string} url
*/
-const getUrl = module => pathToFileURL(module.resource).toString();
+const getUrl = (module) => pathToFileURL(module.resource).toString();
const WorkerSpecifierTag = Symbol("worker specifier tag");
@@ -253,7 +253,7 @@ class WorkerPlugin {
* @param {CallExpression} expr expression
* @returns {boolean | void} true when handled
*/
- const handleNewWorker = expr => {
+ const handleNewWorker = (expr) => {
if (expr.arguments.length === 0 || expr.arguments.length > 2) {
return;
}
@@ -483,7 +483,7 @@ class WorkerPlugin {
/**
* @param {string} item item
*/
- const processItem = item => {
+ const processItem = (item) => {
if (
item.startsWith("*") &&
item.includes(".") &&
@@ -505,7 +505,7 @@ class WorkerPlugin {
}
}
);
- parser.hooks.pattern.for(pattern).tap(PLUGIN_NAME, pattern => {
+ parser.hooks.pattern.for(pattern).tap(PLUGIN_NAME, (pattern) => {
parser.tagVariable(pattern.name, WorkerSpecifierTag);
return true;
});
@@ -530,7 +530,7 @@ class WorkerPlugin {
const source = match[3];
(call ? parser.hooks.call : parser.hooks.new)
.for(harmonySpecifierTag)
- .tap(PLUGIN_NAME, expr => {
+ .tap(PLUGIN_NAME, (expr) => {
const settings = /** @type {HarmonySettings} */ (
parser.currentTagData
);
diff --git a/lib/dependencies/getFunctionExpression.js b/lib/dependencies/getFunctionExpression.js
index f4495b500ff..e213fa6cedd 100644
--- a/lib/dependencies/getFunctionExpression.js
+++ b/lib/dependencies/getFunctionExpression.js
@@ -14,7 +14,7 @@
* @param {Expression | SpreadElement} expr expressions
* @returns {{fn: FunctionExpression | ArrowFunctionExpression, expressions: (Expression | SpreadElement)[], needThis: boolean | undefined } | undefined} function expression with additional information
*/
-module.exports = expr => {
+module.exports = (expr) => {
//
if (
expr.type === "FunctionExpression" ||
diff --git a/lib/esm/ModuleChunkFormatPlugin.js b/lib/esm/ModuleChunkFormatPlugin.js
index 61c18ed15eb..8d26a4314b8 100644
--- a/lib/esm/ModuleChunkFormatPlugin.js
+++ b/lib/esm/ModuleChunkFormatPlugin.js
@@ -119,7 +119,7 @@ class ModuleChunkFormatPlugin {
* @returns {void}
*/
apply(compiler) {
- compiler.hooks.thisCompilation.tap(PLUGIN_NAME, compilation => {
+ compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {
compilation.hooks.additionalChunkRuntimeRequirements.tap(
PLUGIN_NAME,
(chunk, set) => {
@@ -196,17 +196,17 @@ class ModuleChunkFormatPlugin {
const hotUpdateChunk = chunk instanceof HotUpdateChunk ? chunk : null;
const source = new ConcatSource();
source.add(
- `export const __webpack_id__ = ${JSON.stringify(chunk.id)};\n`
+ `export const ${RuntimeGlobals.esmId} = ${JSON.stringify(chunk.id)};\n`
);
source.add(
- `export const __webpack_ids__ = ${JSON.stringify(chunk.ids)};\n`
+ `export const ${RuntimeGlobals.esmIds} = ${JSON.stringify(chunk.ids)};\n`
);
- source.add("export const __webpack_modules__ = ");
+ source.add(`export const ${RuntimeGlobals.esmModules} = `);
source.add(modules);
source.add(";\n");
const runtimeModules = chunkGraph.getChunkRuntimeModulesInOrder(chunk);
if (runtimeModules.length > 0) {
- source.add("export const __webpack_runtime__ =\n");
+ source.add(`export const ${RuntimeGlobals.esmRuntime} =\n`);
source.add(
Template.renderChunkRuntimeModules(runtimeModules, renderContext)
);
diff --git a/lib/esm/ModuleChunkLoadingPlugin.js b/lib/esm/ModuleChunkLoadingPlugin.js
index a34f990a290..01ff5ae05eb 100644
--- a/lib/esm/ModuleChunkLoadingPlugin.js
+++ b/lib/esm/ModuleChunkLoadingPlugin.js
@@ -21,13 +21,13 @@ class ModuleChunkLoadingPlugin {
* @returns {void}
*/
apply(compiler) {
- compiler.hooks.thisCompilation.tap(PLUGIN_NAME, compilation => {
+ compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {
const globalChunkLoading = compilation.outputOptions.chunkLoading;
/**
* @param {Chunk} chunk chunk to check
* @returns {boolean} true, when the plugin is enabled for the chunk
*/
- const isEnabledForChunk = chunk => {
+ const isEnabledForChunk = (chunk) => {
const options = chunk.getEntryOptions();
const chunkLoading =
options && options.chunkLoading !== undefined
diff --git a/lib/esm/ModuleChunkLoadingRuntimeModule.js b/lib/esm/ModuleChunkLoadingRuntimeModule.js
index 7c3e94d136a..3df1e1e3a95 100644
--- a/lib/esm/ModuleChunkLoadingRuntimeModule.js
+++ b/lib/esm/ModuleChunkLoadingRuntimeModule.js
@@ -159,7 +159,7 @@ class ModuleChunkLoadingRuntimeModule extends RuntimeModule {
stateExpression ? `${stateExpression} = ${stateExpression} || ` : ""
}{`,
Template.indent(
- Array.from(initialChunkIds, id => `${JSON.stringify(id)}: 0`).join(
+ Array.from(initialChunkIds, (id) => `${JSON.stringify(id)}: 0`).join(
",\n"
)
),
@@ -168,29 +168,33 @@ class ModuleChunkLoadingRuntimeModule extends RuntimeModule {
withLoading || withExternalInstallChunk
? `var installChunk = ${runtimeTemplate.basicFunction("data", [
runtimeTemplate.destructureObject(
- ["__webpack_ids__", "__webpack_modules__", "__webpack_runtime__"],
+ [
+ RuntimeGlobals.esmIds,
+ RuntimeGlobals.esmModules,
+ RuntimeGlobals.esmRuntime
+ ],
"data"
),
'// add "modules" to the modules object,',
'// then flag all "ids" as loaded and fire callback',
"var moduleId, chunkId, i = 0;",
- "for(moduleId in __webpack_modules__) {",
+ `for(moduleId in ${RuntimeGlobals.esmModules}) {`,
Template.indent([
- `if(${RuntimeGlobals.hasOwnProperty}(__webpack_modules__, moduleId)) {`,
+ `if(${RuntimeGlobals.hasOwnProperty}(${RuntimeGlobals.esmModules}, moduleId)) {`,
Template.indent(
- `${RuntimeGlobals.moduleFactories}[moduleId] = __webpack_modules__[moduleId];`
+ `${RuntimeGlobals.moduleFactories}[moduleId] = ${RuntimeGlobals.esmModules}[moduleId];`
),
"}"
]),
"}",
- `if(__webpack_runtime__) __webpack_runtime__(${RuntimeGlobals.require});`,
- "for(;i < __webpack_ids__.length; i++) {",
+ `if(${RuntimeGlobals.esmRuntime}) ${RuntimeGlobals.esmRuntime}(${RuntimeGlobals.require});`,
+ `for(;i < ${RuntimeGlobals.esmIds}.length; i++) {`,
Template.indent([
- "chunkId = __webpack_ids__[i];",
+ `chunkId = ${RuntimeGlobals.esmIds}[i];`,
`if(${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) && installedChunks[chunkId]) {`,
Template.indent("installedChunks[chunkId][0]();"),
"}",
- "installedChunks[__webpack_ids__[i]] = 0;"
+ `installedChunks[${RuntimeGlobals.esmIds}[i]] = 0;`
]),
"}",
withOnChunkLoad ? `${RuntimeGlobals.onChunksLoaded}();` : ""
@@ -365,8 +369,8 @@ class ModuleChunkLoadingRuntimeModule extends RuntimeModule {
"// start update chunk loading",
`var url = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId);`,
`var onResolve = ${runtimeTemplate.basicFunction("obj", [
- "var updatedModules = obj.__webpack_modules__;",
- "var updatedRuntime = obj.__webpack_runtime__;",
+ `var updatedModules = obj.${RuntimeGlobals.esmModules};`,
+ `var updatedRuntime = obj.${RuntimeGlobals.esmRuntime};`,
"if(updatedRuntime) currentUpdateRuntime.push(updatedRuntime);",
"for(var moduleId in updatedModules) {",
Template.indent([
diff --git a/lib/formatLocation.js b/lib/formatLocation.js
index 780d4a475ca..f75bc73ede1 100644
--- a/lib/formatLocation.js
+++ b/lib/formatLocation.js
@@ -12,7 +12,7 @@
* @param {SourcePosition} pos position
* @returns {string} formatted position
*/
-const formatPosition = pos => {
+const formatPosition = (pos) => {
if (pos && typeof pos === "object") {
if ("line" in pos && "column" in pos) {
return `${pos.line}:${pos.column}`;
@@ -27,7 +27,7 @@ const formatPosition = pos => {
* @param {DependencyLocation} loc location
* @returns {string} formatted location
*/
-const formatLocation = loc => {
+const formatLocation = (loc) => {
if (loc && typeof loc === "object") {
if ("start" in loc && loc.start && "end" in loc && loc.end) {
if (
diff --git a/lib/hmr/HotModuleReplacement.runtime.js b/lib/hmr/HotModuleReplacement.runtime.js
index cb6d22d1562..5f297710e13 100644
--- a/lib/hmr/HotModuleReplacement.runtime.js
+++ b/lib/hmr/HotModuleReplacement.runtime.js
@@ -354,38 +354,50 @@ module.exports = function () {
};
var outdatedModules = [];
- results.forEach(function (result) {
- if (result.apply) {
- var modules = result.apply(reportError);
- if (modules) {
- for (var i = 0; i < modules.length; i++) {
- outdatedModules.push(modules[i]);
- }
- }
- }
- });
- return Promise.all([disposePromise, applyPromise]).then(function () {
- // handle errors in accept handlers and self accepted module load
- if (error) {
- return setStatus("fail").then(function () {
- throw error;
- });
- }
+ var onAccepted = function () {
+ return Promise.all([disposePromise, applyPromise]).then(function () {
+ // handle errors in accept handlers and self accepted module load
+ if (error) {
+ return setStatus("fail").then(function () {
+ throw error;
+ });
+ }
- if (queuedInvalidatedModules) {
- return internalApply(options).then(function (list) {
- outdatedModules.forEach(function (moduleId) {
- if (list.indexOf(moduleId) < 0) list.push(moduleId);
+ if (queuedInvalidatedModules) {
+ return internalApply(options).then(function (list) {
+ outdatedModules.forEach(function (moduleId) {
+ if (list.indexOf(moduleId) < 0) list.push(moduleId);
+ });
+ return list;
});
- return list;
- });
- }
+ }
- return setStatus("idle").then(function () {
- return outdatedModules;
+ return setStatus("idle").then(function () {
+ return outdatedModules;
+ });
});
- });
+ };
+
+ return Promise.all(
+ results
+ .filter(function (result) {
+ return result.apply;
+ })
+ .map(function (result) {
+ return result.apply(reportError);
+ })
+ )
+ .then(function (applyResults) {
+ applyResults.forEach(function (modules) {
+ if (modules) {
+ for (var i = 0; i < modules.length; i++) {
+ outdatedModules.push(modules[i]);
+ }
+ }
+ });
+ })
+ .then(onAccepted);
}
function applyInvalidatedModules() {
diff --git a/lib/hmr/JavascriptHotModuleReplacement.runtime.js b/lib/hmr/JavascriptHotModuleReplacement.runtime.js
index 109a2cea695..fecf52e5c0c 100644
--- a/lib/hmr/JavascriptHotModuleReplacement.runtime.js
+++ b/lib/hmr/JavascriptHotModuleReplacement.runtime.js
@@ -281,6 +281,7 @@ module.exports = function () {
}
},
apply: function (reportError) {
+ var acceptPromises = [];
// insert new code
for (var updateModuleId in appliedUpdate) {
if ($hasOwnProperty$(appliedUpdate, updateModuleId)) {
@@ -317,8 +318,9 @@ module.exports = function () {
}
}
for (var k = 0; k < callbacks.length; k++) {
+ var result;
try {
- callbacks[k].call(null, moduleOutdatedDependencies);
+ result = callbacks[k].call(null, moduleOutdatedDependencies);
} catch (err) {
if (typeof errorHandlers[k] === "function") {
try {
@@ -355,54 +357,63 @@ module.exports = function () {
}
}
}
+ if (result && typeof result.then === "function") {
+ acceptPromises.push(result);
+ }
}
}
}
}
- // Load self accepted modules
- for (var o = 0; o < outdatedSelfAcceptedModules.length; o++) {
- var item = outdatedSelfAcceptedModules[o];
- var moduleId = item.module;
- try {
- item.require(moduleId);
- } catch (err) {
- if (typeof item.errorHandler === "function") {
- try {
- item.errorHandler(err, {
- moduleId: moduleId,
- module: $moduleCache$[moduleId]
- });
- } catch (err1) {
+ var onAccepted = function () {
+ // Load self accepted modules
+ for (var o = 0; o < outdatedSelfAcceptedModules.length; o++) {
+ var item = outdatedSelfAcceptedModules[o];
+ var moduleId = item.module;
+ try {
+ item.require(moduleId);
+ } catch (err) {
+ if (typeof item.errorHandler === "function") {
+ try {
+ item.errorHandler(err, {
+ moduleId: moduleId,
+ module: $moduleCache$[moduleId]
+ });
+ } catch (err1) {
+ if (options.onErrored) {
+ options.onErrored({
+ type: "self-accept-error-handler-errored",
+ moduleId: moduleId,
+ error: err1,
+ originalError: err
+ });
+ }
+ if (!options.ignoreErrored) {
+ reportError(err1);
+ reportError(err);
+ }
+ }
+ } else {
if (options.onErrored) {
options.onErrored({
- type: "self-accept-error-handler-errored",
+ type: "self-accept-errored",
moduleId: moduleId,
- error: err1,
- originalError: err
+ error: err
});
}
if (!options.ignoreErrored) {
- reportError(err1);
reportError(err);
}
}
- } else {
- if (options.onErrored) {
- options.onErrored({
- type: "self-accept-errored",
- moduleId: moduleId,
- error: err
- });
- }
- if (!options.ignoreErrored) {
- reportError(err);
- }
}
}
- }
+ };
- return outdatedModules;
+ return Promise.all(acceptPromises)
+ .then(onAccepted)
+ .then(function () {
+ return outdatedModules;
+ });
}
};
}
diff --git a/lib/hmr/JavascriptHotModuleReplacementHelper.js b/lib/hmr/JavascriptHotModuleReplacementHelper.js
index 9974735732b..935fce0cc7e 100644
--- a/lib/hmr/JavascriptHotModuleReplacementHelper.js
+++ b/lib/hmr/JavascriptHotModuleReplacementHelper.js
@@ -13,7 +13,7 @@ const Template = require("../Template");
* @param {string} type unique identifier used for HMR runtime properties
* @returns {string} HMR runtime code
*/
-const generateJavascriptHMR = type =>
+const generateJavascriptHMR = (type) =>
Template.getFunctionContent(
require("../hmr/JavascriptHotModuleReplacement.runtime")
)
diff --git a/lib/hmr/LazyCompilationPlugin.js b/lib/hmr/LazyCompilationPlugin.js
index e4b4edc6dd1..b37ff4b5974 100644
--- a/lib/hmr/LazyCompilationPlugin.js
+++ b/lib/hmr/LazyCompilationPlugin.js
@@ -382,7 +382,7 @@ class LazyCompilationPlugin {
callback();
});
if (promise && promise.then) {
- promise.then(b => {
+ promise.then((b) => {
backend = b;
callback();
}, callback);
@@ -395,7 +395,7 @@ class LazyCompilationPlugin {
PLUGIN_NAME,
(module, createData, resolveData) => {
if (
- resolveData.dependencies.every(dep =>
+ resolveData.dependencies.every((dep) =>
HMR_DEPENDENCY_TYPES.has(dep.type)
)
) {
@@ -406,9 +406,9 @@ class LazyCompilationPlugin {
/** @type {Module} */
(compilation.moduleGraph.getParentModule(hmrDep));
const isReferringToDynamicImport = originModule.blocks.some(
- block =>
+ (block) =>
block.dependencies.some(
- dep =>
+ (dep) =>
dep.type === "import()" &&
/** @type {HarmonyImportDependency} */ (dep).request ===
hmrDep.request
@@ -417,7 +417,7 @@ class LazyCompilationPlugin {
if (!isReferringToDynamicImport) return module;
} else if (
!resolveData.dependencies.every(
- dep =>
+ (dep) =>
HMR_DEPENDENCY_TYPES.has(dep.type) ||
(this.imports &&
(dep.type === "import()" ||
@@ -455,7 +455,7 @@ class LazyCompilationPlugin {
);
}
);
- compiler.hooks.shutdown.tapAsync(PLUGIN_NAME, callback => {
+ compiler.hooks.shutdown.tapAsync(PLUGIN_NAME, (callback) => {
backend.dispose(callback);
});
}
diff --git a/lib/hmr/lazyCompilationBackend.js b/lib/hmr/lazyCompilationBackend.js
index 31b8ced3b3f..c5fbbbf72ad 100644
--- a/lib/hmr/lazyCompilationBackend.js
+++ b/lib/hmr/lazyCompilationBackend.js
@@ -22,7 +22,7 @@
* @param {Omit & { client: NonNullable}} options additional options for the backend
* @returns {BackendHandler} backend
*/
-module.exports = options => (compiler, callback) => {
+module.exports = (options) => (compiler, callback) => {
const logger = compiler.getInfrastructureLogger("LazyCompilationBackend");
const activeModules = new Map();
const prefix = "/lazy-compilation-using-";
@@ -47,7 +47,7 @@ module.exports = options => (compiler, callback) => {
const listen =
typeof options.listen === "function"
? options.listen
- : server => {
+ : (server) => {
let listen = options.listen;
if (typeof listen === "object" && !("port" in listen)) {
listen = { ...listen, port: undefined };
@@ -100,14 +100,14 @@ module.exports = options => (compiler, callback) => {
let isClosing = false;
/** @type {Set} */
const sockets = new Set();
- server.on("connection", socket => {
+ server.on("connection", (socket) => {
sockets.add(socket);
socket.on("close", () => {
sockets.delete(socket);
});
if (isClosing) socket.destroy();
});
- server.on("clientError", e => {
+ server.on("clientError", (e) => {
if (e.message !== "Server is disposing") logger.warn(e);
});
@@ -117,7 +117,7 @@ module.exports = options => (compiler, callback) => {
* @param {Error} err error
* @returns {void}
*/
- err => {
+ (err) => {
if (err) return callback(err);
const _addr = server.address();
if (typeof _addr === "string") {
@@ -138,7 +138,7 @@ module.exports = options => (compiler, callback) => {
isClosing = true;
// Removing the listener is a workaround for a memory leak in node.js
server.off("request", requestListener);
- server.close(err => {
+ server.close((err) => {
callback(err);
});
for (const socket of sockets) {
diff --git a/lib/ids/ChunkModuleIdRangePlugin.js b/lib/ids/ChunkModuleIdRangePlugin.js
index 3a62447d0a1..a3233bb969c 100644
--- a/lib/ids/ChunkModuleIdRangePlugin.js
+++ b/lib/ids/ChunkModuleIdRangePlugin.js
@@ -39,13 +39,13 @@ class ChunkModuleIdRangePlugin {
*/
apply(compiler) {
const options = this.options;
- compiler.hooks.compilation.tap(PLUGIN_NAME, compilation => {
+ compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
const moduleGraph = compilation.moduleGraph;
- compilation.hooks.moduleIds.tap(PLUGIN_NAME, modules => {
+ compilation.hooks.moduleIds.tap(PLUGIN_NAME, (modules) => {
const chunkGraph = compilation.chunkGraph;
const chunk = find(
compilation.chunks,
- chunk => chunk.name === options.name
+ (chunk) => chunk.name === options.name
);
if (!chunk) {
throw new Error(
@@ -72,7 +72,7 @@ class ChunkModuleIdRangePlugin {
chunkModules = chunkGraph.getOrderedChunkModules(chunk, cmpFn);
} else {
chunkModules = [...modules]
- .filter(m => chunkGraph.isModuleInChunk(m, chunk))
+ .filter((m) => chunkGraph.isModuleInChunk(m, chunk))
.sort(compareModulesByPreOrderIndexOrIdentifier(moduleGraph));
}
diff --git a/lib/ids/DeterministicChunkIdsPlugin.js b/lib/ids/DeterministicChunkIdsPlugin.js
index b4fa8ca2151..d06b7b3a7ec 100644
--- a/lib/ids/DeterministicChunkIdsPlugin.js
+++ b/lib/ids/DeterministicChunkIdsPlugin.js
@@ -37,8 +37,8 @@ class DeterministicChunkIdsPlugin {
* @returns {void}
*/
apply(compiler) {
- compiler.hooks.compilation.tap(PLUGIN_NAME, compilation => {
- compilation.hooks.chunkIds.tap(PLUGIN_NAME, chunks => {
+ compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
+ compilation.hooks.chunkIds.tap(PLUGIN_NAME, (chunks) => {
const chunkGraph = compilation.chunkGraph;
const context = this.options.context
? this.options.context
@@ -49,8 +49,9 @@ class DeterministicChunkIdsPlugin {
const usedIds = getUsedChunkIds(compilation);
assignDeterministicIds(
- [...chunks].filter(chunk => chunk.id === null),
- chunk => getFullChunkName(chunk, chunkGraph, context, compiler.root),
+ [...chunks].filter((chunk) => chunk.id === null),
+ (chunk) =>
+ getFullChunkName(chunk, chunkGraph, context, compiler.root),
compareNatural,
(chunk, id) => {
const size = usedIds.size;
diff --git a/lib/ids/DeterministicModuleIdsPlugin.js b/lib/ids/DeterministicModuleIdsPlugin.js
index 813ab8729c3..7ed80a67ef5 100644
--- a/lib/ids/DeterministicModuleIdsPlugin.js
+++ b/lib/ids/DeterministicModuleIdsPlugin.js
@@ -43,7 +43,7 @@ class DeterministicModuleIdsPlugin {
* @returns {void}
*/
apply(compiler) {
- compiler.hooks.compilation.tap(PLUGIN_NAME, compilation => {
+ compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
compilation.hooks.moduleIds.tap(PLUGIN_NAME, () => {
const chunkGraph = compilation.chunkGraph;
const context = this.options.context
@@ -61,7 +61,7 @@ class DeterministicModuleIdsPlugin {
);
assignDeterministicIds(
modules,
- module => getFullModuleName(module, context, compiler.root),
+ (module) => getFullModuleName(module, context, compiler.root),
failOnConflict
? () => 0
: compareModulesByPreOrderIndexOrIdentifier(
diff --git a/lib/ids/HashedModuleIdsPlugin.js b/lib/ids/HashedModuleIdsPlugin.js
index a67f6e382b8..3944f8d2747 100644
--- a/lib/ids/HashedModuleIdsPlugin.js
+++ b/lib/ids/HashedModuleIdsPlugin.js
@@ -54,7 +54,7 @@ class HashedModuleIdsPlugin {
*/
apply(compiler) {
const options = this.options;
- compiler.hooks.compilation.tap(PLUGIN_NAME, compilation => {
+ compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
compilation.hooks.moduleIds.tap(PLUGIN_NAME, () => {
const chunkGraph = compilation.chunkGraph;
const context = this.options.context
diff --git a/lib/ids/IdHelpers.js b/lib/ids/IdHelpers.js
index 2e97a015ee8..142af991bfd 100644
--- a/lib/ids/IdHelpers.js
+++ b/lib/ids/IdHelpers.js
@@ -33,7 +33,7 @@ const getHash = (str, len, hashFunction) => {
* @param {string} str the string
* @returns {string} string prefixed by an underscore if it is a number
*/
-const avoidNumber = str => {
+const avoidNumber = (str) => {
// max length of a number is 21 chars, bigger numbers a written as "...e+xx"
if (str.length > 21) return str;
const firstChar = str.charCodeAt(0);
@@ -54,7 +54,7 @@ const avoidNumber = str => {
* @param {string} request the request
* @returns {string} id representation
*/
-const requestToId = request =>
+const requestToId = (request) =>
request.replace(/^(\.\.?\/)+/, "").replace(/(^[.-]|[^a-zA-Z0-9_-])+/g, "_");
/**
@@ -136,7 +136,7 @@ const getShortChunkName = (
associatedObjectForCache
) => {
const modules = chunkGraph.getChunkRootModules(chunk);
- const shortModuleNames = modules.map(m =>
+ const shortModuleNames = modules.map((m) =>
requestToId(getShortModuleName(m, context, associatedObjectForCache))
);
chunk.idNameHints.sort();
@@ -164,10 +164,10 @@ const getLongChunkName = (
associatedObjectForCache
) => {
const modules = chunkGraph.getChunkRootModules(chunk);
- const shortModuleNames = modules.map(m =>
+ const shortModuleNames = modules.map((m) =>
requestToId(getShortModuleName(m, context, associatedObjectForCache))
);
- const longModuleNames = modules.map(m =>
+ const longModuleNames = modules.map((m) =>
requestToId(
getLongModuleName("", m, context, hashFunction, associatedObjectForCache)
)
@@ -198,7 +198,7 @@ const getFullChunkName = (
) => {
if (chunk.name) return chunk.name;
const modules = chunkGraph.getChunkRootModules(chunk);
- const fullModuleNames = modules.map(m =>
+ const fullModuleNames = modules.map((m) =>
makePathsRelative(context, m.identifier(), associatedObjectForCache)
);
return fullModuleNames.join();
@@ -259,7 +259,7 @@ const getUsedModuleIdsAndModules = (compilation, filter) => {
* @param {Compilation} compilation the compilation
* @returns {Set} used chunk ids as strings
*/
-const getUsedChunkIds = compilation => {
+const getUsedChunkIds = (compilation) => {
/** @type {Set} */
const usedIds = new Set();
if (compilation.usedChunkIds) {
@@ -413,7 +413,7 @@ const assignAscendingModuleIds = (usedIds, modules, compilation) => {
/**
* @param {Module} module the module
*/
- assignId = module => {
+ assignId = (module) => {
if (chunkGraph.getModuleId(module) === null) {
while (usedIds.has(String(nextId))) nextId++;
chunkGraph.setModuleId(module, nextId++);
@@ -423,7 +423,7 @@ const assignAscendingModuleIds = (usedIds, modules, compilation) => {
/**
* @param {Module} module the module
*/
- assignId = module => {
+ assignId = (module) => {
if (chunkGraph.getModuleId(module) === null) {
chunkGraph.setModuleId(module, nextId++);
}
diff --git a/lib/ids/NamedChunkIdsPlugin.js b/lib/ids/NamedChunkIdsPlugin.js
index 7d4337d45ad..139d4793377 100644
--- a/lib/ids/NamedChunkIdsPlugin.js
+++ b/lib/ids/NamedChunkIdsPlugin.js
@@ -42,24 +42,24 @@ class NamedChunkIdsPlugin {
* @returns {void}
*/
apply(compiler) {
- compiler.hooks.compilation.tap(PLUGIN_NAME, compilation => {
+ compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
const hashFunction =
/** @type {NonNullable