diff --git a/.eslintignore b/.eslintignore
index f3afa1defd0..f595813309c 100644
--- a/.eslintignore
+++ b/.eslintignore
@@ -25,5 +25,6 @@ schemas/**/*.check.js
# Ignore some examples files
examples/**/*.js
+examples/**/*.mjs
!examples/*/webpack.config.js
diff --git a/.eslintrc.js b/.eslintrc.js
index a8e25bd729e..fb78a264ea8 100644
--- a/.eslintrc.js
+++ b/.eslintrc.js
@@ -1,15 +1,19 @@
module.exports = {
root: true,
- plugins: ["prettier", "node", "jest", "jsdoc"],
+ reportUnusedDisableDirectives: true,
+ plugins: ["prettier", "n", "jest", "jsdoc"],
extends: [
"eslint:recommended",
- "plugin:node/recommended",
+ "plugin:n/recommended",
"plugin:prettier/recommended"
],
env: {
node: true,
es6: true
},
+ globals: {
+ WebAssembly: true
+ },
parserOptions: {
ecmaVersion: 2018
},
@@ -26,7 +30,7 @@ module.exports = {
"no-use-before-define": "off",
"no-unused-vars": ["error", { args: "none", ignoreRestSiblings: true }],
"no-loop-func": "off",
- "node/no-missing-require": ["error", { allowModules: ["webpack"] }],
+ "n/no-missing-require": ["error", { allowModules: ["webpack"] }],
"jsdoc/check-indentation": "error",
"jsdoc/check-param-names": "error",
"jsdoc/check-property-names": "error",
@@ -116,6 +120,14 @@ module.exports = {
nsObj: false,
jasmine: false
}
+ },
+ {
+ files: ["examples/**/*.js"],
+ rules: {
+ "n/no-missing-require": "off",
+ "n/no-unpublished-require": "off",
+ "n/no-extraneous-require": "off"
+ }
}
]
};
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
index c6b24d47388..89efe54b7d5 100644
--- a/.github/PULL_REQUEST_TEMPLATE.md
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -1,17 +1,22 @@
-
-
-## Summary
+
+
+**What kind of change does this PR introduce?**
+
+
+
+**Did you add tests for your changes?**
-
+
-copilot:summary
+**Does this PR introduce a breaking change?**
-## Details
+
-
+**What needs to be documented once your changes are merged?**
-copilot:walkthrough
+
+
diff --git a/.github/PULL_REQUEST_TEMPLATE_ORIGINAL.md b/.github/PULL_REQUEST_TEMPLATE_ORIGINAL.md
deleted file mode 100644
index 89efe54b7d5..00000000000
--- a/.github/PULL_REQUEST_TEMPLATE_ORIGINAL.md
+++ /dev/null
@@ -1,22 +0,0 @@
-
-
-
-
-
-
-**What kind of change does this PR introduce?**
-
-
-
-**Did you add tests for your changes?**
-
-
-
-**Does this PR introduce a breaking change?**
-
-
-
-**What needs to be documented once your changes are merged?**
-
-
-
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index ebd98cfae21..0d610ef58b4 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -19,14 +19,14 @@ jobs:
lint:
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
- name: Use Node.js
- uses: actions/setup-node@v3
+ uses: actions/setup-node@v4
with:
- node-version: 16.x
+ node-version: lts/*
cache: "yarn"
- run: yarn --frozen-lockfile
- - uses: actions/cache@v3
+ - uses: actions/cache@v4
with:
path: .eslintcache
key: lint-${{ env.GITHUB_SHA }}
@@ -35,9 +35,9 @@ jobs:
basic:
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
- name: Use Node.js
- uses: actions/setup-node@v3
+ uses: actions/setup-node@v4
with:
node-version: 16.x
cache: "yarn"
@@ -45,16 +45,16 @@ jobs:
- run: yarn link --frozen-lockfile || true
- run: yarn link webpack --frozen-lockfile
- run: yarn test:basic --ci
- - uses: codecov/codecov-action@v3
+ - uses: codecov/codecov-action@v4
with:
flags: basic
functionalities: gcov
validate-legacy-node:
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
- name: Use Node.js
- uses: actions/setup-node@v3
+ uses: actions/setup-node@v4
with:
node-version: 10.x
cache: "yarn"
@@ -64,22 +64,22 @@ jobs:
unit:
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
- name: Use Node.js
- uses: actions/setup-node@v3
+ uses: actions/setup-node@v4
with:
node-version: 16.x
cache: "yarn"
- run: yarn --frozen-lockfile
- run: yarn link --frozen-lockfile || true
- run: yarn link webpack --frozen-lockfile
- - uses: actions/cache@v3
+ - uses: actions/cache@v4
with:
path: .jest-cache
key: jest-unit-${{ env.GITHUB_SHA }}
restore-keys: jest-unit-
- run: yarn cover:unit --ci --cacheDirectory .jest-cache
- - uses: codecov/codecov-action@v3
+ - uses: codecov/codecov-action@v4
with:
flags: unit
functionalities: gcov
@@ -115,9 +115,9 @@ jobs:
use_main_branches: 1
runs-on: ${{ matrix.os }}
steps:
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
- name: Use Node.js ${{ matrix.node-version }}
- uses: actions/setup-node@v3
+ uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
cache: "yarn"
@@ -134,14 +134,14 @@ jobs:
if: matrix.node-version != '10.x' && matrix.node-version != '12.x' && matrix.node-version != '14.x'
- run: yarn link --frozen-lockfile || true
- run: yarn link webpack --frozen-lockfile
- - uses: actions/cache@v3
+ - uses: actions/cache@v4
with:
path: .jest-cache
key: jest-integration-${{ env.GITHUB_SHA }}
restore-keys: jest-integration-
- run: yarn cover:integration:${{ matrix.part }} --ci --cacheDirectory .jest-cache || yarn cover:integration:${{ matrix.part }} --ci --cacheDirectory .jest-cache -f
- run: yarn cover:merge
- - uses: codecov/codecov-action@v3
+ - uses: codecov/codecov-action@v4
with:
flags: integration
functionalities: gcov
diff --git a/.prettierignore b/.prettierignore
index e1bc031979d..eeb72ea7218 100644
--- a/.prettierignore
+++ b/.prettierignore
@@ -29,3 +29,5 @@ schemas/**/*.check.js
# Ignore example fixtures
examples/
!examples/**/webpack.config.js
+
+.vscode/**/*.*
diff --git a/README.md b/README.md
index bde462e6739..ccc4c80b123 100644
--- a/README.md
+++ b/README.md
@@ -38,6 +38,9 @@
+
+
+
webpack
Webpack is a module bundler. Its main purpose is to bundle JavaScript files for usage in a browser, yet it is also capable of transforming, bundling, or packaging just about any resource or asset.
diff --git a/bin/webpack.js b/bin/webpack.js
index 615c86ac845..1ee7e0dd2d0 100755
--- a/bin/webpack.js
+++ b/bin/webpack.js
@@ -76,11 +76,10 @@ const isInstalled = packageName => {
const runCli = cli => {
const path = require("path");
const pkgPath = require.resolve(`${cli.package}/package.json`);
- // eslint-disable-next-line node/no-missing-require
const pkg = require(pkgPath);
if (pkg.type === "module" || /\.mjs/i.test(pkg.bin[cli.binName])) {
- // eslint-disable-next-line node/no-unsupported-features/es-syntax
+ // eslint-disable-next-line n/no-unsupported-features/es-syntax
import(path.resolve(path.dirname(pkgPath), pkg.bin[cli.binName])).catch(
error => {
console.error(error);
@@ -88,7 +87,6 @@ const runCli = cli => {
}
);
} else {
- // eslint-disable-next-line node/no-missing-require
require(path.resolve(path.dirname(pkgPath), pkg.bin[cli.binName]));
}
};
diff --git a/cspell.json b/cspell.json
index 180091c6728..f93f32eb526 100644
--- a/cspell.json
+++ b/cspell.json
@@ -27,6 +27,7 @@
"browserified",
"browserslist",
"browserslistrc",
+ "browsertest",
"Brumme",
"bugfix",
"bugfixes",
@@ -129,6 +130,7 @@
"loadername",
"loglevel",
"longnameforexport",
+ "longtest",
"mangleable",
"MCEP",
"mebibytes",
diff --git a/declarations/WebpackOptions.d.ts b/declarations/WebpackOptions.d.ts
index 8ff9aa91ec4..45cf35995a2 100644
--- a/declarations/WebpackOptions.d.ts
+++ b/declarations/WebpackOptions.d.ts
@@ -35,6 +35,14 @@ export type Context = string;
* References to other configurations to depend on.
*/
export type Dependencies = string[];
+/**
+ * Options for the webpack-dev-server.
+ */
+export type DevServer =
+ | false
+ | {
+ [k: string]: any;
+ };
/**
* A developer tool to enhance debugging (false | eval | [inline-|hidden-|eval-][nosources-][cheap-[module-]]source-map).
*/
@@ -728,6 +736,14 @@ export type AssetParserDataUrlFunction = (
source: string | Buffer,
context: {filename: string; module: import("../lib/Module")}
) => boolean;
+/**
+ * Avoid generating and loading a stylesheet and only embed exports from css into output javascript files.
+ */
+export type CssGeneratorExportsOnly = boolean;
+/**
+ * Use ES modules named export for css exports.
+ */
+export type CssParserNamedExports = boolean;
/**
* A Function returning a Promise resolving to a normalized entry.
*/
@@ -1047,12 +1063,6 @@ export interface FileCacheOptions {
*/
version?: string;
}
-/**
- * Options for the webpack-dev-server.
- */
-export interface DevServer {
- [k: string]: any;
-}
/**
* Multiple entry bundles are created. The key is the entry name. The value can be a string, an array or an entry description object.
*/
@@ -1636,11 +1646,17 @@ export interface NodeOptions {
/**
* Include a polyfill for the '__dirname' variable.
*/
- __dirname?: false | true | "warn-mock" | "mock" | "eval-only";
+ __dirname?: false | true | "warn-mock" | "mock" | "node-module" | "eval-only";
/**
* Include a polyfill for the '__filename' variable.
*/
- __filename?: false | true | "warn-mock" | "mock" | "eval-only";
+ __filename?:
+ | false
+ | true
+ | "warn-mock"
+ | "mock"
+ | "node-module"
+ | "eval-only";
/**
* Include a polyfill for the 'global' variable.
*/
@@ -2237,6 +2253,10 @@ export interface Environment {
* The environment supports arrow functions ('() => { ... }').
*/
arrowFunction?: boolean;
+ /**
+ * The environment supports async function and await ('async function () { await ... }').
+ */
+ asyncFunction?: boolean;
/**
* The environment supports BigInt as literal (123n).
*/
@@ -2376,6 +2396,10 @@ export interface SnapshotOptions {
*/
timestamp?: boolean;
};
+ /**
+ * List of paths that are not managed by a package manager and the contents are subject to change.
+ */
+ unmanagedPaths?: (RegExp | string)[];
}
/**
* Stats options object.
@@ -2804,22 +2828,77 @@ export interface AssetResourceGeneratorOptions {
publicPath?: RawPublicPath;
}
/**
- * Options for css handling.
+ * Generator options for css/auto modules.
*/
-export interface CssExperimentOptions {
+export interface CssAutoGeneratorOptions {
/**
* Avoid generating and loading a stylesheet and only embed exports from css into output javascript files.
*/
- exportsOnly?: boolean;
+ exportsOnly?: CssGeneratorExportsOnly;
+}
+/**
+ * Parser options for css/auto modules.
+ */
+export interface CssAutoParserOptions {
+ /**
+ * Use ES modules named export for css exports.
+ */
+ namedExports?: CssParserNamedExports;
}
/**
* Generator options for css modules.
*/
-export interface CssGeneratorOptions {}
+export interface CssGeneratorOptions {
+ /**
+ * Avoid generating and loading a stylesheet and only embed exports from css into output javascript files.
+ */
+ exportsOnly?: CssGeneratorExportsOnly;
+}
+/**
+ * Generator options for css/global modules.
+ */
+export interface CssGlobalGeneratorOptions {
+ /**
+ * Avoid generating and loading a stylesheet and only embed exports from css into output javascript files.
+ */
+ exportsOnly?: CssGeneratorExportsOnly;
+}
+/**
+ * Parser options for css/global modules.
+ */
+export interface CssGlobalParserOptions {
+ /**
+ * Use ES modules named export for css exports.
+ */
+ namedExports?: CssParserNamedExports;
+}
+/**
+ * Generator options for css/module modules.
+ */
+export interface CssModuleGeneratorOptions {
+ /**
+ * Avoid generating and loading a stylesheet and only embed exports from css into output javascript files.
+ */
+ exportsOnly?: CssGeneratorExportsOnly;
+}
+/**
+ * Parser options for css/module modules.
+ */
+export interface CssModuleParserOptions {
+ /**
+ * Use ES modules named export for css exports.
+ */
+ namedExports?: CssParserNamedExports;
+}
/**
* Parser options for css modules.
*/
-export interface CssParserOptions {}
+export interface CssParserOptions {
+ /**
+ * Use ES modules named export for css exports.
+ */
+ namedExports?: CssParserNamedExports;
+}
/**
* No generator options are supported for this module type.
*/
@@ -3585,7 +3664,7 @@ export interface ExperimentsExtra {
/**
* Enable css support.
*/
- css?: boolean | CssExperimentOptions;
+ css?: boolean;
/**
* Compile entrypoints and import()s only when they are accessed.
*/
@@ -3602,7 +3681,7 @@ export interface ExperimentsNormalizedExtra {
/**
* Enable css support.
*/
- css?: false | CssExperimentOptions;
+ css?: boolean;
/**
* Compile entrypoints and import()s only when they are accessed.
*/
@@ -3643,6 +3722,22 @@ export interface GeneratorOptionsByModuleTypeKnown {
* Generator options for asset/resource modules.
*/
"asset/resource"?: AssetResourceGeneratorOptions;
+ /**
+ * Generator options for css modules.
+ */
+ css?: CssGeneratorOptions;
+ /**
+ * Generator options for css/auto modules.
+ */
+ "css/auto"?: CssAutoGeneratorOptions;
+ /**
+ * Generator options for css/global modules.
+ */
+ "css/global"?: CssGlobalGeneratorOptions;
+ /**
+ * Generator options for css/module modules.
+ */
+ "css/module"?: CssModuleGeneratorOptions;
/**
* No generator options are supported for this module type.
*/
@@ -3691,6 +3786,22 @@ export interface ParserOptionsByModuleTypeKnown {
* No parser options are supported for this module type.
*/
"asset/source"?: EmptyParserOptions;
+ /**
+ * Parser options for css modules.
+ */
+ css?: CssParserOptions;
+ /**
+ * Parser options for css/auto modules.
+ */
+ "css/auto"?: CssAutoParserOptions;
+ /**
+ * Parser options for css/global modules.
+ */
+ "css/global"?: CssGlobalParserOptions;
+ /**
+ * Parser options for css/module modules.
+ */
+ "css/module"?: CssModuleParserOptions;
/**
* Parser options for javascript modules.
*/
diff --git a/examples/aggressive-merging/webpack.config.js b/examples/aggressive-merging/webpack.config.js
index 2887ce355e8..8bc21bfad40 100644
--- a/examples/aggressive-merging/webpack.config.js
+++ b/examples/aggressive-merging/webpack.config.js
@@ -1,5 +1,5 @@
var path = require("path");
-var { AggressiveMergingPlugin } = require("../../").optimize;
+var { AggressiveMergingPlugin } = require("../..").optimize;
module.exports = {
// mode: "development" || "production",
diff --git a/examples/build-common.js b/examples/build-common.js
index 3b7d512d393..7293b32d604 100644
--- a/examples/build-common.js
+++ b/examples/build-common.js
@@ -51,7 +51,30 @@ const doCompileAndReplace = (args, prefix, callback) => {
throw new Error("Please install webpack-cli at root.");
}
- cp.exec(`node ${path.resolve(__dirname, "../bin/webpack.js")} ${args} ${displayReasons} ${commonArgs}`, (error, stdout, stderr) => {
+ const connectIO = (subprocess) => {
+ const { stdin, stdout, stderr } = process;
+ const { stdin: _stdin, stdout: _stdout, stderr: _stderr } = subprocess;
+ const inputPair = [[stdin, _stdin]];
+ const outputPair = [[stdout, _stdout], [stderr, _stderr]];
+ inputPair.forEach(pair => {
+ pair[0].pipe(pair[1])
+ })
+ outputPair.forEach(pair => {
+ pair[1].pipe(pair[0])
+ })
+ disconnectIO = () => {
+ inputPair.forEach(pair => {
+ pair[0].unpipe(pair[1])
+ })
+ outputPair.forEach(pair => {
+ pair[1].unpipe(pair[0])
+ })
+ }
+ }
+ let disconnectIO = null;
+
+ const subprocess = cp.exec(`node ${path.resolve(__dirname, "../bin/webpack.js")} ${args} ${displayReasons} ${commonArgs}`, (error, stdout, stderr) => {
+ disconnectIO && disconnectIO();
if (stderr)
console.log(stderr);
if (error !== null)
@@ -64,6 +87,7 @@ const doCompileAndReplace = (args, prefix, callback) => {
}
callback();
});
+ connectIO(subprocess);
};
async.series([
diff --git a/examples/dll-user/webpack.config.js b/examples/dll-user/webpack.config.js
index c8d0d5210ad..7aae24a69ab 100644
--- a/examples/dll-user/webpack.config.js
+++ b/examples/dll-user/webpack.config.js
@@ -5,11 +5,11 @@ module.exports = {
plugins: [
new webpack.DllReferencePlugin({
context: path.join(__dirname, "..", "dll"),
- manifest: require("../dll/dist/alpha-manifest.json") // eslint-disable-line
+ manifest: require("../dll/dist/alpha-manifest.json")
}),
new webpack.DllReferencePlugin({
scope: "beta",
- manifest: require("../dll/dist/beta-manifest.json"), // eslint-disable-line
+ manifest: require("../dll/dist/beta-manifest.json"),
extensions: [".js", ".jsx"]
})
]
diff --git a/examples/stats-detailed/README.md b/examples/stats-detailed/README.md
new file mode 100644
index 00000000000..18e05d2780f
--- /dev/null
+++ b/examples/stats-detailed/README.md
@@ -0,0 +1,83 @@
+This configuration will enable the detailed output for the stats report.
+
+You see that everything is working nicely together.
+
+# example.js
+
+```javascript
+console.log("Hello World!");
+```
+
+# webpack.config.js
+
+```javascript
+const path = require("path");
+
+module.exports = {
+ output: {
+ path: path.join(__dirname, "dist"),
+ filename: "output.js"
+ },
+ stats: "detailed"
+};
+```
+
+# dist/output.js
+
+```javascript
+/******/ (() => { // webpackBootstrap
+var __webpack_exports__ = {};
+/*!********************!*\
+ !*** ./example.js ***!
+ \********************/
+/*! unknown exports (runtime-defined) */
+/*! runtime requirements: */
+console.log("Hello World!");
+
+/******/ })()
+;
+```
+
+# Info
+
+## Production mode
+
+```
+PublicPath: dist/
+asset output.js 28 bytes {179} [emitted] [minimized] (name: main)
+Entrypoint main 28 bytes = output.js
+chunk {179} (runtime: main) output.js (main) 29 bytes [entry] [rendered]
+ > ./example.js main
+./example.js [144] 29 bytes {179} [depth 0] [built] [code generated]
+ [no exports used]
+ Statement (ExpressionStatement) with side effects in source code at 1:0-28
+ ModuleConcatenation bailout: Module is not an ECMAScript module
+
+LOG from webpack.Compilation
+ 1 modules hashed, 0 from cache (1 variants per module in average)
+ 100% code generated (1 generated, 0 from cache)
++ 24 hidden lines
+
+LOG from webpack.FlagDependencyExportsPlugin
+ 0% of exports of modules have been determined (1 no declared exports, 0 not cached, 0 flagged uncacheable, 0 from cache, 0 from mem cache, 0 additional calculations due to dependencies)
++ 3 hidden lines
+
+LOG from webpack.buildChunkGraph
+ 2 queue items processed (1 blocks)
+ 0 chunk groups connected
+ 0 chunk groups processed for merging (0 module sets, 0 forked, 0 + 0 modules forked, 0 + 0 modules merged into fork, 0 resulting modules)
+ 0 chunk group info updated (0 already connected chunk groups reconnected)
++ 5 hidden lines
+
+LOG from webpack.FileSystemInfo
+ 1 new snapshots created
+ 0% root snapshot uncached (0 / 0)
+ 0% children snapshot uncached (0 / 0)
+ 0 entries tested
+ File info in cache: 1 timestamps 1 hashes 1 timestamp hash combinations
+ File timestamp hash combination snapshot optimization: 0% (0/1) entries shared via 0 shared snapshots (0 times referenced)
+ Directory info in cache: 0 timestamps 0 hashes 0 timestamp hash combinations
+ Managed items info in cache: 0 items
+
+2023-06-23 22:57:08: webpack 5.88.0 compiled successfully (208f5e6e78a48d3e157f)
+```
diff --git a/examples/stats-detailed/build.js b/examples/stats-detailed/build.js
new file mode 100644
index 00000000000..6da1216015d
--- /dev/null
+++ b/examples/stats-detailed/build.js
@@ -0,0 +1,4 @@
+global.NO_REASONS = true;
+global.NO_STATS_OPTIONS = true;
+global.STATS_COLORS = true;
+require("../build-common");
diff --git a/examples/stats-detailed/example.js b/examples/stats-detailed/example.js
new file mode 100644
index 00000000000..019c0f4bc8e
--- /dev/null
+++ b/examples/stats-detailed/example.js
@@ -0,0 +1 @@
+console.log("Hello World!");
diff --git a/examples/stats-detailed/template.md b/examples/stats-detailed/template.md
new file mode 100644
index 00000000000..d475f06a46f
--- /dev/null
+++ b/examples/stats-detailed/template.md
@@ -0,0 +1,29 @@
+This configuration will enable the detailed output for the stats report.
+
+You see that everything is working nicely together.
+
+# example.js
+
+```javascript
+_{{example.js}}_
+```
+
+# webpack.config.js
+
+```javascript
+_{{webpack.config.js}}_
+```
+
+# dist/output.js
+
+```javascript
+_{{dist/output.js}}_
+```
+
+# Info
+
+## Production mode
+
+```
+_{{production:stdout}}_
+```
diff --git a/examples/stats-detailed/webpack.config.js b/examples/stats-detailed/webpack.config.js
new file mode 100644
index 00000000000..a237a81fc37
--- /dev/null
+++ b/examples/stats-detailed/webpack.config.js
@@ -0,0 +1,9 @@
+const path = require("path");
+
+module.exports = {
+ output: {
+ path: path.join(__dirname, "dist"),
+ filename: "output.js"
+ },
+ stats: "detailed"
+};
diff --git a/examples/stats-none/README.md b/examples/stats-none/README.md
new file mode 100644
index 00000000000..b1fe4195d04
--- /dev/null
+++ b/examples/stats-none/README.md
@@ -0,0 +1,47 @@
+This configuration will enable the none output for the stats report.
+
+You see that everything is working nicely together.
+
+# example.js
+
+```javascript
+console.log("Hello World!");
+```
+
+# webpack.config.js
+
+```javascript
+const path = require("path");
+
+module.exports = {
+ output: {
+ path: path.join(__dirname, "dist"),
+ filename: "output.js"
+ },
+ stats: "none"
+};
+```
+
+# dist/output.js
+
+```javascript
+/******/ (() => { // webpackBootstrap
+var __webpack_exports__ = {};
+/*!********************!*\
+ !*** ./example.js ***!
+ \********************/
+/*! unknown exports (runtime-defined) */
+/*! runtime requirements: */
+console.log("Hello World!");
+
+/******/ })()
+;
+```
+
+# Info
+
+## Production mode
+
+```
+
+```
diff --git a/examples/stats-none/build.js b/examples/stats-none/build.js
new file mode 100644
index 00000000000..6da1216015d
--- /dev/null
+++ b/examples/stats-none/build.js
@@ -0,0 +1,4 @@
+global.NO_REASONS = true;
+global.NO_STATS_OPTIONS = true;
+global.STATS_COLORS = true;
+require("../build-common");
diff --git a/examples/stats-none/example.js b/examples/stats-none/example.js
new file mode 100644
index 00000000000..019c0f4bc8e
--- /dev/null
+++ b/examples/stats-none/example.js
@@ -0,0 +1 @@
+console.log("Hello World!");
diff --git a/examples/stats-none/template.md b/examples/stats-none/template.md
new file mode 100644
index 00000000000..b60135662a4
--- /dev/null
+++ b/examples/stats-none/template.md
@@ -0,0 +1,29 @@
+This configuration will enable the none output for the stats report.
+
+You see that everything is working nicely together.
+
+# example.js
+
+```javascript
+_{{example.js}}_
+```
+
+# webpack.config.js
+
+```javascript
+_{{webpack.config.js}}_
+```
+
+# dist/output.js
+
+```javascript
+_{{dist/output.js}}_
+```
+
+# Info
+
+## Production mode
+
+```
+_{{production:stdout}}_
+```
diff --git a/examples/stats-none/webpack.config.js b/examples/stats-none/webpack.config.js
new file mode 100644
index 00000000000..8a687239693
--- /dev/null
+++ b/examples/stats-none/webpack.config.js
@@ -0,0 +1,9 @@
+const path = require("path");
+
+module.exports = {
+ output: {
+ path: path.join(__dirname, "dist"),
+ filename: "output.js"
+ },
+ stats: "none"
+};
diff --git a/examples/stats-normal/README.md b/examples/stats-normal/README.md
new file mode 100644
index 00000000000..becfd3e06c1
--- /dev/null
+++ b/examples/stats-normal/README.md
@@ -0,0 +1,49 @@
+This configuration will enable the normal output for the stats report.
+
+You see that everything is working nicely together.
+
+# example.js
+
+```javascript
+console.log("Hello World!");
+```
+
+# webpack.config.js
+
+```javascript
+const path = require("path");
+
+module.exports = {
+ output: {
+ path: path.join(__dirname, "dist"),
+ filename: "output.js"
+ },
+ stats: "normal"
+};
+```
+
+# dist/output.js
+
+```javascript
+/******/ (() => { // webpackBootstrap
+var __webpack_exports__ = {};
+/*!********************!*\
+ !*** ./example.js ***!
+ \********************/
+/*! unknown exports (runtime-defined) */
+/*! runtime requirements: */
+console.log("Hello World!");
+
+/******/ })()
+;
+```
+
+# Info
+
+## Production mode
+
+```
+asset output.js 28 bytes [emitted] [minimized] (name: main)
+./example.js 29 bytes [built] [code generated]
+webpack 5.88.0 compiled successfully
+```
\ No newline at end of file
diff --git a/examples/stats-normal/build.js b/examples/stats-normal/build.js
new file mode 100644
index 00000000000..6da1216015d
--- /dev/null
+++ b/examples/stats-normal/build.js
@@ -0,0 +1,4 @@
+global.NO_REASONS = true;
+global.NO_STATS_OPTIONS = true;
+global.STATS_COLORS = true;
+require("../build-common");
diff --git a/examples/stats-normal/example.js b/examples/stats-normal/example.js
new file mode 100644
index 00000000000..019c0f4bc8e
--- /dev/null
+++ b/examples/stats-normal/example.js
@@ -0,0 +1 @@
+console.log("Hello World!");
diff --git a/examples/stats-normal/template.md b/examples/stats-normal/template.md
new file mode 100644
index 00000000000..ed4c81681b5
--- /dev/null
+++ b/examples/stats-normal/template.md
@@ -0,0 +1,29 @@
+This configuration will enable the normal output for the stats report.
+
+You see that everything is working nicely together.
+
+# example.js
+
+```javascript
+_{{example.js}}_
+```
+
+# webpack.config.js
+
+```javascript
+_{{webpack.config.js}}_
+```
+
+# dist/output.js
+
+```javascript
+_{{dist/output.js}}_
+```
+
+# Info
+
+## Production mode
+
+```
+_{{production:stdout}}_
+```
\ No newline at end of file
diff --git a/examples/stats-normal/webpack.config.js b/examples/stats-normal/webpack.config.js
new file mode 100644
index 00000000000..e741993c8d9
--- /dev/null
+++ b/examples/stats-normal/webpack.config.js
@@ -0,0 +1,9 @@
+const path = require("path");
+
+module.exports = {
+ output: {
+ path: path.join(__dirname, "dist"),
+ filename: "output.js"
+ },
+ stats: "normal"
+};
diff --git a/examples/stats-summary/README.md b/examples/stats-summary/README.md
new file mode 100644
index 00000000000..7ebee7c56d0
--- /dev/null
+++ b/examples/stats-summary/README.md
@@ -0,0 +1,47 @@
+This configuration will enable the summary output for the stats report.
+
+You see that everything is working nicely together.
+
+# example.js
+
+```javascript
+console.log("Hello World!");
+```
+
+# webpack.config.js
+
+```javascript
+const path = require("path");
+
+module.exports = {
+ output: {
+ path: path.join(__dirname, "dist"),
+ filename: "output.js"
+ },
+ stats: "summary"
+};
+```
+
+# dist/output.js
+
+```javascript
+/******/ (() => { // webpackBootstrap
+var __webpack_exports__ = {};
+/*!********************!*\
+ !*** ./example.js ***!
+ \********************/
+/*! unknown exports (runtime-defined) */
+/*! runtime requirements: */
+console.log("Hello World!");
+
+/******/ })()
+;
+```
+
+# Info
+
+## Production mode
+
+```
+webpack 5.88.0 compiled successfully
+```
diff --git a/examples/stats-summary/build.js b/examples/stats-summary/build.js
new file mode 100644
index 00000000000..6da1216015d
--- /dev/null
+++ b/examples/stats-summary/build.js
@@ -0,0 +1,4 @@
+global.NO_REASONS = true;
+global.NO_STATS_OPTIONS = true;
+global.STATS_COLORS = true;
+require("../build-common");
diff --git a/examples/stats-summary/example.js b/examples/stats-summary/example.js
new file mode 100644
index 00000000000..019c0f4bc8e
--- /dev/null
+++ b/examples/stats-summary/example.js
@@ -0,0 +1 @@
+console.log("Hello World!");
diff --git a/examples/stats-summary/template.md b/examples/stats-summary/template.md
new file mode 100644
index 00000000000..087cfc32b5f
--- /dev/null
+++ b/examples/stats-summary/template.md
@@ -0,0 +1,29 @@
+This configuration will enable the summary output for the stats report.
+
+You see that everything is working nicely together.
+
+# example.js
+
+```javascript
+_{{example.js}}_
+```
+
+# webpack.config.js
+
+```javascript
+_{{webpack.config.js}}_
+```
+
+# dist/output.js
+
+```javascript
+_{{dist/output.js}}_
+```
+
+# Info
+
+## Production mode
+
+```
+_{{production:stdout}}_
+```
diff --git a/examples/stats-summary/webpack.config.js b/examples/stats-summary/webpack.config.js
new file mode 100644
index 00000000000..94e9a0f0b2d
--- /dev/null
+++ b/examples/stats-summary/webpack.config.js
@@ -0,0 +1,9 @@
+const path = require("path");
+
+module.exports = {
+ output: {
+ path: path.join(__dirname, "dist"),
+ filename: "output.js"
+ },
+ stats: "summary"
+};
diff --git a/examples/wasm-bindgen-esm/README.md b/examples/wasm-bindgen-esm/README.md
index e316207b016..8d5e4c44a8a 100644
--- a/examples/wasm-bindgen-esm/README.md
+++ b/examples/wasm-bindgen-esm/README.md
@@ -26,17 +26,18 @@ document.write(greeting('Bob'));
/*! runtime requirements: __webpack_require__, __webpack_require__.r, __webpack_exports__, module, __webpack_require__.a, __webpack_require__.* */
/***/ ((module, __webpack_exports__, __webpack_require__) => {
-__webpack_require__.a(module, async (__webpack_handle_async_dependencies__) => {
+__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _pkg__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./pkg */ 1);
var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_pkg__WEBPACK_IMPORTED_MODULE_0__]);
-_pkg__WEBPACK_IMPORTED_MODULE_0__ = (__webpack_async_dependencies__.then ? await __webpack_async_dependencies__ : __webpack_async_dependencies__)[0];
+_pkg__WEBPACK_IMPORTED_MODULE_0__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0];
document.write((0,_pkg__WEBPACK_IMPORTED_MODULE_0__.greeting)('Bob'));
-});
+__webpack_async_result__();
+} catch(e) { __webpack_async_result__(e); } });
/***/ }),
/* 1 */
@@ -49,14 +50,14 @@ document.write((0,_pkg__WEBPACK_IMPORTED_MODULE_0__.greeting)('Bob'));
/*! runtime requirements: __webpack_require__, __webpack_require__.r, __webpack_exports__, module, __webpack_require__.a, __webpack_require__.d, __webpack_require__.* */
/***/ ((__webpack_module__, __webpack_exports__, __webpack_require__) => {
-__webpack_require__.a(__webpack_module__, async (__webpack_handle_async_dependencies__) => {
+__webpack_require__.a(__webpack_module__, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
-/* harmony export */ "greeting": () => (/* binding */ greeting)
+/* harmony export */ greeting: () => (/* binding */ greeting)
/* harmony export */ });
/* harmony import */ var _hi_wasm_bg_wasm__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./hi_wasm_bg.wasm */ 2);
var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_hi_wasm_bg_wasm__WEBPACK_IMPORTED_MODULE_0__]);
-_hi_wasm_bg_wasm__WEBPACK_IMPORTED_MODULE_0__ = (__webpack_async_dependencies__.then ? await __webpack_async_dependencies__ : __webpack_async_dependencies__)[0];
+_hi_wasm_bg_wasm__WEBPACK_IMPORTED_MODULE_0__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0];
let WASM_VECTOR_LEN = 0;
@@ -161,7 +162,8 @@ function greeting(name) {
}
-});
+__webpack_async_result__();
+} catch(e) { __webpack_async_result__(e); } });
/***/ }),
/* 2 */
@@ -216,75 +218,70 @@ module.exports = __webpack_require__.v(exports, module.id, "ffe21e855d11d22ab54f
/************************************************************************/
/******/ /* webpack/runtime/async module */
/******/ (() => {
-/******/ var webpackThen = typeof Symbol === "function" ? Symbol("webpack then") : "__webpack_then__";
+/******/ var webpackQueues = typeof Symbol === "function" ? Symbol("webpack queues") : "__webpack_queues__";
/******/ var webpackExports = typeof Symbol === "function" ? Symbol("webpack exports") : "__webpack_exports__";
-/******/ var completeQueue = (queue) => {
-/******/ if(queue) {
+/******/ var webpackError = typeof Symbol === "function" ? Symbol("webpack error") : "__webpack_error__";
+/******/ var resolveQueue = (queue) => {
+/******/ if(queue && queue.d < 1) {
+/******/ queue.d = 1;
/******/ queue.forEach((fn) => (fn.r--));
/******/ queue.forEach((fn) => (fn.r-- ? fn.r++ : fn()));
/******/ }
/******/ }
-/******/ var completeFunction = (fn) => (!--fn.r && fn());
-/******/ var queueFunction = (queue, fn) => (queue ? queue.push(fn) : completeFunction(fn));
/******/ var wrapDeps = (deps) => (deps.map((dep) => {
/******/ if(dep !== null && typeof dep === "object") {
-/******/ if(dep[webpackThen]) return dep;
+/******/ if(dep[webpackQueues]) return dep;
/******/ if(dep.then) {
/******/ var queue = [];
+/******/ queue.d = 0;
/******/ dep.then((r) => {
/******/ obj[webpackExports] = r;
-/******/ completeQueue(queue);
-/******/ queue = 0;
+/******/ resolveQueue(queue);
+/******/ }, (e) => {
+/******/ obj[webpackError] = e;
+/******/ resolveQueue(queue);
/******/ });
/******/ var obj = {};
-/******/ obj[webpackThen] = (fn, reject) => (queueFunction(queue, fn), dep.catch(reject));
+/******/ obj[webpackQueues] = (fn) => (fn(queue));
/******/ return obj;
/******/ }
/******/ }
/******/ var ret = {};
-/******/ ret[webpackThen] = (fn) => (completeFunction(fn));
-/******/ ret[webpackExports] = dep;
-/******/ return ret;
+/******/ ret[webpackQueues] = x => {};
+/******/ ret[webpackExports] = dep;
+/******/ return ret;
/******/ }));
/******/ __webpack_require__.a = (module, body, hasAwait) => {
-/******/ var queue = hasAwait && [];
+/******/ var queue;
+/******/ hasAwait && ((queue = []).d = -1);
+/******/ var depQueues = new Set();
/******/ var exports = module.exports;
/******/ var currentDeps;
/******/ var outerResolve;
/******/ var reject;
-/******/ var isEvaluating = true;
-/******/ var nested = false;
-/******/ var whenAll = (deps, onResolve, onReject) => {
-/******/ if (nested) return;
-/******/ nested = true;
-/******/ onResolve.r += deps.length;
-/******/ deps.map((dep, i) => (dep[webpackThen](onResolve, onReject)));
-/******/ nested = false;
-/******/ };
/******/ var promise = new Promise((resolve, rej) => {
/******/ reject = rej;
-/******/ outerResolve = () => (resolve(exports), completeQueue(queue), queue = 0);
+/******/ outerResolve = resolve;
/******/ });
/******/ promise[webpackExports] = exports;
-/******/ promise[webpackThen] = (fn, rejectFn) => {
-/******/ if (isEvaluating) { return completeFunction(fn); }
-/******/ if (currentDeps) whenAll(currentDeps, fn, rejectFn);
-/******/ queueFunction(queue, fn);
-/******/ promise.catch(rejectFn);
-/******/ };
+/******/ promise[webpackQueues] = (fn) => (queue && fn(queue), depQueues.forEach(fn), promise["catch"](x => {}));
/******/ module.exports = promise;
/******/ body((deps) => {
-/******/ if(!deps) return outerResolve();
/******/ currentDeps = wrapDeps(deps);
-/******/ var fn, result;
-/******/ var promise = new Promise((resolve, reject) => {
-/******/ fn = () => (resolve(result = currentDeps.map((d) => (d[webpackExports]))));
+/******/ var fn;
+/******/ var getResult = () => (currentDeps.map((d) => {
+/******/ if(d[webpackError]) throw d[webpackError];
+/******/ return d[webpackExports];
+/******/ }))
+/******/ var promise = new Promise((resolve) => {
+/******/ fn = () => (resolve(getResult));
/******/ fn.r = 0;
-/******/ whenAll(currentDeps, fn, reject);
+/******/ var fnQueue = (q) => (q !== queue && !depQueues.has(q) && (depQueues.add(q), q && !q.d && (fn.r++, q.push(fn))));
+/******/ currentDeps.map((dep) => (dep[webpackQueues](fnQueue)));
/******/ });
-/******/ return fn.r ? promise : result;
-/******/ }).then(outerResolve, reject);
-/******/ isEvaluating = false;
+/******/ return fn.r ? promise : getResult();
+/******/ }, (err) => ((err ? reject(promise[webpackError] = err) : outerResolve(exports)), resolveQueue(queue)));
+/******/ queue && queue.d < 0 && (queue.d = 0);
/******/ };
/******/ })();
/******/
@@ -320,14 +317,26 @@ module.exports = __webpack_require__.v(exports, module.id, "ffe21e855d11d22ab54f
/******/ (() => {
/******/ __webpack_require__.v = (exports, wasmModuleId, wasmModuleHash, importsObj) => {
/******/ var req = fetch(__webpack_require__.p + "" + wasmModuleHash + ".wasm");
-/******/ if (typeof WebAssembly.instantiateStreaming === 'function') {
-/******/ return WebAssembly.instantiateStreaming(req, importsObj)
-/******/ .then((res) => (Object.assign(exports, res.instance.exports)));
-/******/ }
-/******/ return req
+/******/ var fallback = () => (req
/******/ .then((x) => (x.arrayBuffer()))
/******/ .then((bytes) => (WebAssembly.instantiate(bytes, importsObj)))
-/******/ .then((res) => (Object.assign(exports, res.instance.exports)));
+/******/ .then((res) => (Object.assign(exports, res.instance.exports))));
+/******/ return req.then((res) => {
+/******/ if (typeof WebAssembly.instantiateStreaming === "function") {
+/******/ return WebAssembly.instantiateStreaming(res, importsObj)
+/******/ .then(
+/******/ (res) => (Object.assign(exports, res.instance.exports)),
+/******/ (e) => {
+/******/ if(res.headers.get("Content-Type") !== "application/wasm") {
+/******/ console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e);
+/******/ return fallback();
+/******/ }
+/******/ throw e;
+/******/ }
+/******/ );
+/******/ }
+/******/ return fallback();
+/******/ });
/******/ };
/******/ })();
/******/
@@ -358,30 +367,30 @@ module.exports = __webpack_require__.v(exports, module.id, "ffe21e855d11d22ab54f
```
asset ffe21e855d11d22ab54f.wasm 14.8 KiB [emitted] [immutable] (auxiliary name: main)
-asset output.js 12.8 KiB [emitted] (name: main)
-chunk (runtime: main) output.js (main) 3.03 KiB (javascript) 14.8 KiB (webassembly) 3.35 KiB (runtime) [entry] [rendered]
+asset output.js 13.4 KiB [emitted] (name: main)
+chunk (runtime: main) output.js (main) 3.03 KiB (javascript) 14.8 KiB (webassembly) 3.68 KiB (runtime) [entry] [rendered]
> ./example.js main
- runtime modules 3.35 KiB 6 modules
+ runtime modules 3.68 KiB 6 modules
dependent modules 2.97 KiB (javascript) 14.8 KiB (webassembly) [dependent] 2 modules
./example.js 69 bytes [built] [code generated]
[no exports]
[used exports unknown]
entry ./example.js main
-webpack 5.53.0 compiled successfully
+webpack 5.90.0 compiled successfully
```
## Production mode
```
asset f7199313c1125f249cd6.wasm 14.8 KiB [emitted] [immutable] (auxiliary name: main)
-asset output.js 2.96 KiB [emitted] [minimized] (name: main)
-chunk (runtime: main) output.js (main) 3.03 KiB (javascript) 14.8 KiB (webassembly) 3.08 KiB (runtime) [entry] [rendered]
+asset output.js 3.41 KiB [emitted] [minimized] (name: main)
+chunk (runtime: main) output.js (main) 3.03 KiB (javascript) 14.8 KiB (webassembly) 3.42 KiB (runtime) [entry] [rendered]
> ./example.js main
- runtime modules 3.08 KiB 5 modules
+ runtime modules 3.42 KiB 5 modules
dependent modules 2.97 KiB (javascript) 14.8 KiB (webassembly) [dependent] 2 modules
./example.js 69 bytes [built] [code generated]
[no exports]
[no exports used]
entry ./example.js main
-webpack 5.53.0 compiled successfully
+webpack 5.90.0 compiled successfully
```
diff --git a/examples/wasm-complex/README.md b/examples/wasm-complex/README.md
index 913b4cedce4..1ee4a1db3d9 100644
--- a/examples/wasm-complex/README.md
+++ b/examples/wasm-complex/README.md
@@ -120,9 +120,9 @@ __webpack_async_result__();
__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
-/* harmony export */ "get": () => (/* reexport safe */ _magic_wat__WEBPACK_IMPORTED_MODULE_0__.get),
-/* harmony export */ "getNumber": () => (/* reexport safe */ _magic_wat__WEBPACK_IMPORTED_MODULE_0__.getNumber),
-/* harmony export */ "set": () => (/* reexport safe */ _magic_wat__WEBPACK_IMPORTED_MODULE_0__.set)
+/* harmony export */ get: () => (/* reexport safe */ _magic_wat__WEBPACK_IMPORTED_MODULE_0__.get),
+/* harmony export */ getNumber: () => (/* reexport safe */ _magic_wat__WEBPACK_IMPORTED_MODULE_0__.getNumber),
+/* harmony export */ set: () => (/* reexport safe */ _magic_wat__WEBPACK_IMPORTED_MODULE_0__.set)
/* harmony export */ });
/* harmony import */ var _magic_wat__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./magic.wat */ 2);
var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_magic_wat__WEBPACK_IMPORTED_MODULE_0__]);
@@ -188,7 +188,7 @@ __webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __we
__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
-/* harmony export */ "memory": () => (/* binding */ memory)
+/* harmony export */ memory: () => (/* binding */ memory)
/* harmony export */ });
async function getMemoryFromParentInWorker() {
await new Promise(r => setTimeout(r, 200));
@@ -215,8 +215,8 @@ __webpack_async_result__();
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
-/* harmony export */ "getNumber": () => (/* binding */ getNumber),
-/* harmony export */ "getRandomNumber": () => (/* binding */ getRandomNumber)
+/* harmony export */ getNumber: () => (/* binding */ getNumber),
+/* harmony export */ getRandomNumber: () => (/* binding */ getRandomNumber)
/* harmony export */ });
function getNumber() {
return 42;
@@ -266,7 +266,7 @@ function getRandomNumber() {
/******/ var webpackExports = typeof Symbol === "function" ? Symbol("webpack exports") : "__webpack_exports__";
/******/ var webpackError = typeof Symbol === "function" ? Symbol("webpack error") : "__webpack_error__";
/******/ var resolveQueue = (queue) => {
-/******/ if(queue && !queue.d) {
+/******/ if(queue && queue.d < 1) {
/******/ queue.d = 1;
/******/ queue.forEach((fn) => (fn.r--));
/******/ queue.forEach((fn) => (fn.r-- ? fn.r++ : fn()));
@@ -297,7 +297,7 @@ function getRandomNumber() {
/******/ }));
/******/ __webpack_require__.a = (module, body, hasAwait) => {
/******/ var queue;
-/******/ hasAwait && ((queue = []).d = 1);
+/******/ hasAwait && ((queue = []).d = -1);
/******/ var depQueues = new Set();
/******/ var exports = module.exports;
/******/ var currentDeps;
@@ -325,7 +325,7 @@ function getRandomNumber() {
/******/ });
/******/ return fn.r ? promise : getResult();
/******/ }, (err) => ((err ? reject(promise[webpackError] = err) : outerResolve(exports)), resolveQueue(queue)));
-/******/ queue && (queue.d = 0);
+/******/ queue && queue.d < 0 && (queue.d = 0);
/******/ };
/******/ })();
/******/
@@ -361,14 +361,26 @@ function getRandomNumber() {
/******/ (() => {
/******/ __webpack_require__.v = (exports, wasmModuleId, wasmModuleHash, importsObj) => {
/******/ var req = fetch(__webpack_require__.p + "" + wasmModuleHash + ".module.wasm");
-/******/ if (typeof WebAssembly.instantiateStreaming === 'function') {
-/******/ return WebAssembly.instantiateStreaming(req, importsObj)
-/******/ .then((res) => (Object.assign(exports, res.instance.exports)));
-/******/ }
-/******/ return req
+/******/ var fallback = () => (req
/******/ .then((x) => (x.arrayBuffer()))
/******/ .then((bytes) => (WebAssembly.instantiate(bytes, importsObj)))
-/******/ .then((res) => (Object.assign(exports, res.instance.exports)));
+/******/ .then((res) => (Object.assign(exports, res.instance.exports))));
+/******/ return req.then((res) => {
+/******/ if (typeof WebAssembly.instantiateStreaming === "function") {
+/******/ return WebAssembly.instantiateStreaming(res, importsObj)
+/******/ .then(
+/******/ (res) => (Object.assign(exports, res.instance.exports)),
+/******/ (e) => {
+/******/ if(res.headers.get("Content-Type") !== "application/wasm") {
+/******/ console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e);
+/******/ return fallback();
+/******/ }
+/******/ throw e;
+/******/ }
+/******/ );
+/******/ }
+/******/ return fallback();
+/******/ });
/******/ };
/******/ })();
/******/
@@ -398,31 +410,31 @@ function getRandomNumber() {
## Unoptimized
```
-asset output.js 13.2 KiB [emitted] (name: main)
+asset output.js 13.8 KiB [emitted] (name: main)
asset daa529a2a650ee3943a9.module.wasm 139 bytes [emitted] [immutable] (auxiliary name: main)
-chunk (runtime: main) output.js (main) 696 bytes (javascript) 139 bytes (webassembly) 3.24 KiB (runtime) [entry] [rendered]
+chunk (runtime: main) output.js (main) 696 bytes (javascript) 139 bytes (webassembly) 3.69 KiB (runtime) [entry] [rendered]
> ./example.js main
- runtime modules 3.24 KiB 6 modules
+ runtime modules 3.69 KiB 6 modules
dependent modules 449 bytes (javascript) 139 bytes (webassembly) [dependent] 4 modules
./example.js 247 bytes [built] [code generated]
[no exports]
[used exports unknown]
entry ./example.js main
-webpack 5.78.0 compiled successfully
+webpack 5.90.0 compiled successfully
```
## Production mode
```
-asset output.js 2.49 KiB [emitted] [minimized] (name: main)
+asset output.js 2.81 KiB [emitted] [minimized] (name: main)
asset 05aa07f6a3836ded50d1.module.wasm 139 bytes [emitted] [immutable] (auxiliary name: main)
-chunk (runtime: main) output.js (main) 696 bytes (javascript) 139 bytes (webassembly) 2.97 KiB (runtime) [entry] [rendered]
+chunk (runtime: main) output.js (main) 696 bytes (javascript) 139 bytes (webassembly) 3.42 KiB (runtime) [entry] [rendered]
> ./example.js main
- runtime modules 2.97 KiB 5 modules
+ runtime modules 3.42 KiB 5 modules
dependent modules 449 bytes (javascript) 139 bytes (webassembly) [dependent] 4 modules
./example.js 247 bytes [built] [code generated]
[no exports]
[no exports used]
entry ./example.js main
-webpack 5.78.0 compiled successfully
+webpack 5.90.0 compiled successfully
```
diff --git a/examples/wasm-simple/README.md b/examples/wasm-simple/README.md
index fed989d0e64..38a49528e1f 100644
--- a/examples/wasm-simple/README.md
+++ b/examples/wasm-simple/README.md
@@ -134,11 +134,11 @@ module.exports = __webpack_require__.v(exports, module.id, "0eaeab8b9fa3cef100d1
__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
-/* harmony export */ "add": () => (/* reexport safe */ _add_wasm__WEBPACK_IMPORTED_MODULE_0__.add),
-/* harmony export */ "factorial": () => (/* reexport safe */ _factorial_wasm__WEBPACK_IMPORTED_MODULE_1__.factorial),
-/* harmony export */ "factorialJavascript": () => (/* binding */ factorialJavascript),
-/* harmony export */ "fibonacci": () => (/* reexport safe */ _fibonacci_wasm__WEBPACK_IMPORTED_MODULE_2__.fibonacci),
-/* harmony export */ "fibonacciJavascript": () => (/* binding */ fibonacciJavascript)
+/* harmony export */ add: () => (/* reexport safe */ _add_wasm__WEBPACK_IMPORTED_MODULE_0__.add),
+/* harmony export */ factorial: () => (/* reexport safe */ _factorial_wasm__WEBPACK_IMPORTED_MODULE_1__.factorial),
+/* harmony export */ factorialJavascript: () => (/* binding */ factorialJavascript),
+/* harmony export */ fibonacci: () => (/* reexport safe */ _fibonacci_wasm__WEBPACK_IMPORTED_MODULE_2__.fibonacci),
+/* harmony export */ fibonacciJavascript: () => (/* binding */ fibonacciJavascript)
/* harmony export */ });
/* harmony import */ var _add_wasm__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./add.wasm */ 1);
/* harmony import */ var _factorial_wasm__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./factorial.wasm */ 3);
@@ -229,7 +229,7 @@ module.exports = __webpack_require__.v(exports, module.id, "5a6637e8d63cdf9c72da
/******/ var webpackExports = typeof Symbol === "function" ? Symbol("webpack exports") : "__webpack_exports__";
/******/ var webpackError = typeof Symbol === "function" ? Symbol("webpack error") : "__webpack_error__";
/******/ var resolveQueue = (queue) => {
-/******/ if(queue && !queue.d) {
+/******/ if(queue && queue.d < 1) {
/******/ queue.d = 1;
/******/ queue.forEach((fn) => (fn.r--));
/******/ queue.forEach((fn) => (fn.r-- ? fn.r++ : fn()));
@@ -260,7 +260,7 @@ module.exports = __webpack_require__.v(exports, module.id, "5a6637e8d63cdf9c72da
/******/ }));
/******/ __webpack_require__.a = (module, body, hasAwait) => {
/******/ var queue;
-/******/ hasAwait && ((queue = []).d = 1);
+/******/ hasAwait && ((queue = []).d = -1);
/******/ var depQueues = new Set();
/******/ var exports = module.exports;
/******/ var currentDeps;
@@ -288,7 +288,7 @@ module.exports = __webpack_require__.v(exports, module.id, "5a6637e8d63cdf9c72da
/******/ });
/******/ return fn.r ? promise : getResult();
/******/ }, (err) => ((err ? reject(promise[webpackError] = err) : outerResolve(exports)), resolveQueue(queue)));
-/******/ queue && (queue.d = 0);
+/******/ queue && queue.d < 0 && (queue.d = 0);
/******/ };
/******/ })();
/******/
@@ -324,14 +324,26 @@ module.exports = __webpack_require__.v(exports, module.id, "5a6637e8d63cdf9c72da
/******/ (() => {
/******/ __webpack_require__.v = (exports, wasmModuleId, wasmModuleHash, importsObj) => {
/******/ var req = fetch(__webpack_require__.p + "" + wasmModuleHash + ".wasm");
-/******/ if (typeof WebAssembly.instantiateStreaming === 'function') {
-/******/ return WebAssembly.instantiateStreaming(req, importsObj)
-/******/ .then((res) => (Object.assign(exports, res.instance.exports)));
-/******/ }
-/******/ return req
+/******/ var fallback = () => (req
/******/ .then((x) => (x.arrayBuffer()))
/******/ .then((bytes) => (WebAssembly.instantiate(bytes, importsObj)))
-/******/ .then((res) => (Object.assign(exports, res.instance.exports)));
+/******/ .then((res) => (Object.assign(exports, res.instance.exports))));
+/******/ return req.then((res) => {
+/******/ if (typeof WebAssembly.instantiateStreaming === "function") {
+/******/ return WebAssembly.instantiateStreaming(res, importsObj)
+/******/ .then(
+/******/ (res) => (Object.assign(exports, res.instance.exports)),
+/******/ (e) => {
+/******/ if(res.headers.get("Content-Type") !== "application/wasm") {
+/******/ console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e);
+/******/ return fallback();
+/******/ }
+/******/ throw e;
+/******/ }
+/******/ );
+/******/ }
+/******/ return fallback();
+/******/ });
/******/ };
/******/ })();
/******/
@@ -361,35 +373,35 @@ module.exports = __webpack_require__.v(exports, module.id, "5a6637e8d63cdf9c72da
## Unoptimized
```
-asset output.js 12.6 KiB [emitted] (name: main)
+asset output.js 13.2 KiB [emitted] (name: main)
asset 5a6637e8d63cdf9c72da.wasm 67 bytes [emitted] [immutable] (auxiliary name: main)
asset 35a58b7c95860d720a3c.wasm 62 bytes [emitted] [immutable] (auxiliary name: main)
asset 0eaeab8b9fa3cef100d1.wasm 41 bytes [emitted] [immutable] (auxiliary name: main)
-chunk (runtime: main) output.js (main) 1.27 KiB (javascript) 170 bytes (webassembly) 3.23 KiB (runtime) [entry] [rendered]
+chunk (runtime: main) output.js (main) 1.27 KiB (javascript) 170 bytes (webassembly) 3.68 KiB (runtime) [entry] [rendered]
> ./example.js main
- runtime modules 3.23 KiB 6 modules
+ runtime modules 3.68 KiB 6 modules
dependent modules 552 bytes (javascript) 170 bytes (webassembly) [dependent] 4 modules
./example.js 753 bytes [built] [code generated]
[no exports]
[used exports unknown]
entry ./example.js main
-webpack 5.78.0 compiled successfully
+webpack 5.90.0 compiled successfully
```
## Production mode
```
-asset output.js 2.57 KiB [emitted] [minimized] (name: main)
+asset output.js 2.89 KiB [emitted] [minimized] (name: main)
asset 67aca7a09456080b5120.wasm 67 bytes [emitted] [immutable] (auxiliary name: main)
asset 36825f9224dde8d88de0.wasm 62 bytes [emitted] [immutable] (auxiliary name: main)
asset 10cff76bc58b7aa8f9cb.wasm 41 bytes [emitted] [immutable] (auxiliary name: main)
-chunk (runtime: main) output.js (main) 1.27 KiB (javascript) 170 bytes (webassembly) 2.96 KiB (runtime) [entry] [rendered]
+chunk (runtime: main) output.js (main) 1.27 KiB (javascript) 170 bytes (webassembly) 3.42 KiB (runtime) [entry] [rendered]
> ./example.js main
- runtime modules 2.96 KiB 5 modules
+ runtime modules 3.42 KiB 5 modules
dependent modules 552 bytes (javascript) 170 bytes (webassembly) [dependent] 4 modules
./example.js 753 bytes [built] [code generated]
[no exports]
[no exports used]
entry ./example.js main
-webpack 5.78.0 compiled successfully
+webpack 5.90.0 compiled successfully
```
diff --git a/hot/log.js b/hot/log.js
index 81bc8524b45..281771d11ec 100644
--- a/hot/log.js
+++ b/hot/log.js
@@ -45,11 +45,9 @@ module.exports = function (level, msg) {
}
};
-/* eslint-disable node/no-unsupported-features/node-builtins */
var group = console.group || dummy;
var groupCollapsed = console.groupCollapsed || dummy;
var groupEnd = console.groupEnd || dummy;
-/* eslint-enable node/no-unsupported-features/node-builtins */
module.exports.group = logGroup(group);
diff --git a/jest.config.js b/jest.config.js
new file mode 100644
index 00000000000..2cc6d151b2e
--- /dev/null
+++ b/jest.config.js
@@ -0,0 +1,54 @@
+/** @type {import('jest').Config} */
+const config = {
+ prettierPath: require.resolve("prettier-2"),
+ forceExit: true,
+ setupFilesAfterEnv: ["/test/setupTestFramework.js"],
+ testMatch: [
+ "/test/*.test.js",
+ "/test/*.basictest.js",
+ "/test/*.longtest.js",
+ "/test/*.unittest.js"
+ ],
+ watchPathIgnorePatterns: [
+ "/.git",
+ "/node_modules",
+ "/test/js",
+ "/test/browsertest/js",
+ "/test/fixtures/temp-cache-fixture",
+ "/test/fixtures/temp-",
+ "/benchmark",
+ "/assembly",
+ "/tooling",
+ "/examples/*/dist",
+ "/coverage",
+ "/.eslintcache"
+ ],
+ modulePathIgnorePatterns: [
+ "/.git",
+ "/node_modules/webpack/node_modules",
+ "/test/js",
+ "/test/browsertest/js",
+ "/test/fixtures/temp-cache-fixture",
+ "/test/fixtures/temp-",
+ "/benchmark",
+ "/examples/*/dist",
+ "/coverage",
+ "/.eslintcache"
+ ],
+ transformIgnorePatterns: [""],
+ coverageDirectory: "/coverage",
+ coveragePathIgnorePatterns: [
+ "\\.runtime\\.js$",
+ "/test",
+ "/schemas",
+ "/node_modules"
+ ],
+ testEnvironment: "./test/patch-node-env.js",
+ coverageReporters: ["json"],
+ snapshotFormat: {
+ escapeString: true,
+ printBasicPrototype: true
+ }
+};
+
+module.exports = config;
diff --git a/lib/APIPlugin.js b/lib/APIPlugin.js
index cd4dd872199..cc13392b85d 100644
--- a/lib/APIPlugin.js
+++ b/lib/APIPlugin.js
@@ -24,10 +24,12 @@ const ChunkNameRuntimeModule = require("./runtime/ChunkNameRuntimeModule");
const GetFullHashRuntimeModule = require("./runtime/GetFullHashRuntimeModule");
/** @typedef {import("./Compiler")} Compiler */
+/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */
/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */
+/** @typedef {import("./javascript/JavascriptParser").Range} Range */
/**
- * @param {boolean} module true if ES module
+ * @param {boolean | undefined} module true if ES module
* @param {string} importMetaName `import.meta` name
* @returns {Record} replacements
*/
@@ -150,7 +152,9 @@ class APIPlugin {
compiler.hooks.compilation.tap(
PLUGIN_NAME,
(compilation, { normalModuleFactory }) => {
- const { importMetaName } = compilation.outputOptions;
+ const importMetaName = /** @type {string} */ (
+ compilation.outputOptions.importMetaName
+ );
const REPLACEMENTS = getReplacements(
this.options.module,
importMetaName
@@ -166,7 +170,7 @@ class APIPlugin {
.tap(PLUGIN_NAME, chunk => {
compilation.addRuntimeModule(
chunk,
- new ChunkNameRuntimeModule(chunk.name)
+ new ChunkNameRuntimeModule(/** @type {string} */ (chunk.name))
);
return true;
});
@@ -218,7 +222,7 @@ class APIPlugin {
if (info.assign === false) {
parser.hooks.assign.for(key).tap(PLUGIN_NAME, expr => {
const err = new WebpackError(`${key} must not be assigned`);
- err.loc = expr.loc;
+ err.loc = /** @type {DependencyLocation} */ (expr.loc);
throw err;
});
}
@@ -234,9 +238,9 @@ class APIPlugin {
.tap(PLUGIN_NAME, expr => {
const dep = new ConstDependency(
JSON.stringify(parser.state.module.layer),
- expr.range
+ /** @type {Range} */ (expr.range)
);
- dep.loc = expr.loc;
+ dep.loc = /** @type {DependencyLocation} */ (expr.loc);
parser.state.module.addPresentationalDependency(dep);
return true;
});
@@ -247,8 +251,8 @@ class APIPlugin {
? new BasicEvaluatedExpression().setNull()
: new BasicEvaluatedExpression().setString(
parser.state.module.layer
- )
- ).setRange(expr.range)
+ )
+ ).setRange(/** @type {Range} */ (expr.range))
);
parser.hooks.evaluateTypeof
.for("__webpack_layer__")
@@ -257,7 +261,7 @@ class APIPlugin {
.setString(
parser.state.module.layer === null ? "object" : "string"
)
- .setRange(expr.range)
+ .setRange(/** @type {Range} */ (expr.range))
);
parser.hooks.expression
@@ -267,10 +271,10 @@ class APIPlugin {
"__webpack_module__.id";
const dep = new ConstDependency(
parser.state.module.moduleArgument + ".id",
- expr.range,
+ /** @type {Range} */ (expr.range),
[RuntimeGlobals.moduleId]
);
- dep.loc = expr.loc;
+ dep.loc = /** @type {DependencyLocation} */ (expr.loc);
parser.state.module.addPresentationalDependency(dep);
return true;
});
@@ -282,10 +286,10 @@ class APIPlugin {
"__webpack_module__";
const dep = new ConstDependency(
parser.state.module.moduleArgument,
- expr.range,
+ /** @type {Range} */ (expr.range),
[RuntimeGlobals.module]
);
- dep.loc = expr.loc;
+ dep.loc = /** @type {DependencyLocation} */ (expr.loc);
parser.state.module.addPresentationalDependency(dep);
return true;
});
diff --git a/lib/ChunkGraph.js b/lib/ChunkGraph.js
index a191435197b..0b27a2f6751 100644
--- a/lib/ChunkGraph.js
+++ b/lib/ChunkGraph.js
@@ -1539,7 +1539,7 @@ Caller might not support runtime-dependent code generation (opt-out via optimiza
return withConnections
? BigInt(
`0x${this._getModuleGraphHashWithConnections(cgm, module, runtime)}`
- )
+ )
: this._getModuleGraphHashBigInt(cgm, module, runtime);
}
diff --git a/lib/CleanPlugin.js b/lib/CleanPlugin.js
index 6e5c3b0f7d5..534af201a61 100644
--- a/lib/CleanPlugin.js
+++ b/lib/CleanPlugin.js
@@ -328,18 +328,18 @@ class CleanPlugin {
typeof keep === "function"
? keep
: typeof keep === "string"
- ? /**
- * @param {string} path path
- * @returns {boolean} true, if the path should be kept
- */
- path => path.startsWith(keep)
- : typeof keep === "object" && keep.test
- ? /**
- * @param {string} path path
- * @returns {boolean} true, if the path should be kept
- */
- path => keep.test(path)
- : () => false;
+ ? /**
+ * @param {string} path path
+ * @returns {boolean} true, if the path should be kept
+ */
+ path => path.startsWith(keep)
+ : typeof keep === "object" && keep.test
+ ? /**
+ * @param {string} path path
+ * @returns {boolean} true, if the path should be kept
+ */
+ path => keep.test(path)
+ : () => false;
// We assume that no external modification happens while the compiler is active
// So we can store the old assets and only diff to them to avoid fs access on
diff --git a/lib/Compilation.js b/lib/Compilation.js
index a880195717b..1c23bbfa5fd 100644
--- a/lib/Compilation.js
+++ b/lib/Compilation.js
@@ -885,6 +885,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
this.resolverFactory = compiler.resolverFactory;
this.inputFileSystem = compiler.inputFileSystem;
this.fileSystemInfo = new FileSystemInfo(this.inputFileSystem, {
+ unmanagedPaths: compiler.unmanagedPaths,
managedPaths: compiler.managedPaths,
immutablePaths: compiler.immutablePaths,
logger: this.getLogger("webpack.FileSystemInfo"),
@@ -1086,7 +1087,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
}
/**
- * @param {StatsOptions | string} optionsOrPreset stats option value
+ * @param {StatsOptions | string | undefined} optionsOrPreset stats option value
* @param {CreateStatsOptionsContext} context context
* @returns {NormalizedStatsOptions} normalized options
*/
@@ -1177,9 +1178,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
};
if (this.hooks.log.call(name, logEntry) === undefined) {
if (logEntry.type === LogType.profileEnd) {
- // eslint-disable-next-line node/no-unsupported-features/node-builtins
if (typeof console.profileEnd === "function") {
- // eslint-disable-next-line node/no-unsupported-features/node-builtins
console.profileEnd(`[${name}] ${logEntry.args[0]}`);
}
}
@@ -1192,9 +1191,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
}
logEntries.push(logEntry);
if (logEntry.type === LogType.profile) {
- // eslint-disable-next-line node/no-unsupported-features/node-builtins
if (typeof console.profile === "function") {
- // eslint-disable-next-line node/no-unsupported-features/node-builtins
console.profile(`[${name}] ${logEntry.args[0]}`);
}
}
@@ -1725,6 +1722,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
originModule,
module,
true,
+ false,
callback
);
}
@@ -1744,6 +1742,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
* @property {string=} context
* @property {boolean=} recursive recurse into dependencies of the created module
* @property {boolean=} connectOrigin connect the resolved module with the origin module
+ * @property {boolean=} checkCycle check the cycle dependencies of the created module
*/
/**
@@ -1759,7 +1758,8 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
contextInfo,
context,
recursive = true,
- connectOrigin = recursive
+ connectOrigin = recursive,
+ checkCycle = !recursive
},
callback
) {
@@ -1880,6 +1880,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
originModule,
module,
recursive,
+ checkCycle,
callback
);
});
@@ -1887,10 +1888,16 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
);
}
- _handleModuleBuildAndDependencies(originModule, module, recursive, callback) {
+ _handleModuleBuildAndDependencies(
+ originModule,
+ module,
+ recursive,
+ checkCycle,
+ callback
+ ) {
// Check for cycles when build is trigger inside another build
let creatingModuleDuringBuildSet = undefined;
- if (!recursive && this.buildQueue.isProcessing(originModule)) {
+ if (checkCycle && this.buildQueue.isProcessing(originModule)) {
// Track build dependency
creatingModuleDuringBuildSet =
this.creatingModuleDuringBuild.get(originModule);
@@ -1988,8 +1995,8 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
context: context
? context
: originModule
- ? originModule.context
- : this.compiler.context,
+ ? originModule.context
+ : this.compiler.context,
dependencies: dependencies
},
(err, result) => {
@@ -2668,9 +2675,9 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
loaders
? `${
modules.length
- } x ${moduleType} with ${this.requestShortener.shorten(
+ } x ${moduleType} with ${this.requestShortener.shorten(
loaders
- )}`
+ )}`
: `${modules.length} x ${moduleType}`
}`
);
@@ -3078,7 +3085,7 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
`BREAKING CHANGE: No more changes should happen to Compilation.assets after sealing the Compilation.
Do changes to assets earlier, e. g. in Compilation.hooks.processAssets.
Make sure to select an appropriate stage from Compilation.PROCESS_ASSETS_STAGE_*.`
- )
+ )
: Object.freeze(this.assets);
this.summarizeDependencies();
@@ -3341,6 +3348,7 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
dependencyTemplates,
runtimeTemplate,
runtime,
+ runtimes,
codeGenerationResults: results,
compilation: this
});
@@ -4584,8 +4592,8 @@ This prevents using hashes of each other and should be avoided.`);
(typeof file === "string"
? file
: typeof filenameTemplate === "string"
- ? filenameTemplate
- : "");
+ ? filenameTemplate
+ : "");
this.errors.push(new ChunkRenderError(chunk, filename, err));
inTry = false;
@@ -4607,7 +4615,7 @@ This prevents using hashes of each other and should be avoided.`);
? {
...pathAndInfo.info,
...fileManifest.info
- }
+ }
: pathAndInfo.info;
}
@@ -4927,7 +4935,8 @@ This prevents using hashes of each other and should be avoided.`);
hashFunction,
runtimeTemplate,
hashDigest,
- hashDigestLength
+ hashDigestLength,
+ errors
);
}
diff --git a/lib/Compiler.js b/lib/Compiler.js
index 7cc074860b9..685a93c72d4 100644
--- a/lib/Compiler.js
+++ b/lib/Compiler.js
@@ -228,6 +228,8 @@ class Compiler {
/** @type {Set} */
this.managedPaths = new Set();
/** @type {Set} */
+ this.unmanagedPaths = new Set();
+ /** @type {Set} */
this.immutablePaths = new Set();
/** @type {ReadonlySet | undefined} */
@@ -381,6 +383,17 @@ class Compiler {
// e.g. move compilation specific info from Modules into ModuleGraph
_cleanupLastCompilation() {
if (this._lastCompilation !== undefined) {
+ for (const childCompilation of this._lastCompilation.children) {
+ for (const module of childCompilation.modules) {
+ ChunkGraph.clearChunkGraphForModule(module);
+ ModuleGraph.clearModuleGraphForModule(module);
+ module.cleanupForCache();
+ }
+ for (const chunk of childCompilation.chunks) {
+ ChunkGraph.clearChunkGraphForChunk(chunk);
+ }
+ }
+
for (const module of this._lastCompilation.modules) {
ChunkGraph.clearChunkGraphForModule(module);
ModuleGraph.clearModuleGraphForModule(module);
diff --git a/lib/ConcatenationScope.js b/lib/ConcatenationScope.js
index 8c26166b153..aa8a0ed7189 100644
--- a/lib/ConcatenationScope.js
+++ b/lib/ConcatenationScope.js
@@ -114,8 +114,8 @@ class ConcatenationScope {
const asiSafeFlag = asiSafe
? "_asiSafe1"
: asiSafe === false
- ? "_asiSafe0"
- : "";
+ ? "_asiSafe0"
+ : "";
const exportData = ids
? Buffer.from(JSON.stringify(ids), "utf-8").toString("hex")
: "ns";
diff --git a/lib/ConditionalInitFragment.js b/lib/ConditionalInitFragment.js
index 93402f5b50d..54abfd7c7bc 100644
--- a/lib/ConditionalInitFragment.js
+++ b/lib/ConditionalInitFragment.js
@@ -62,8 +62,8 @@ class ConditionalInitFragment extends InitFragment {
}
/**
- * @param {Context} context context
- * @returns {string|Source} the source code that will be included as initialization code
+ * @param {GenerateContext} context context
+ * @returns {string | Source} the source code that will be included as initialization code
*/
getContent(context) {
if (this.runtimeCondition === false || !this.content) return "";
@@ -79,7 +79,7 @@ class ConditionalInitFragment extends InitFragment {
}
/**
- * @param {Context} context context
+ * @param {GenerateContext} context context
* @returns {string|Source=} the source code that will be included at the end of the module
*/
getEndContent(context) {
diff --git a/lib/ContextModule.js b/lib/ContextModule.js
index 2100481f2ac..d39f8f88098 100644
--- a/lib/ContextModule.js
+++ b/lib/ContextModule.js
@@ -509,8 +509,8 @@ class ContextModule extends Module {
this.context
? [this.context]
: typeof this.options.resource === "string"
- ? [this.options.resource]
- : /** @type {string[]} */ (this.options.resource),
+ ? [this.options.resource]
+ : /** @type {string[]} */ (this.options.resource),
null,
SNAPSHOT_OPTIONS,
(err, snapshot) => {
@@ -947,8 +947,8 @@ module.exports = webpackAsyncContext;`;
const requestPrefix = hasNoChunk
? "Promise.resolve()"
: hasMultipleOrNoChunks
- ? `Promise.all(ids.slice(${chunksStartPosition}).map(${RuntimeGlobals.ensureChunk}))`
- : `${RuntimeGlobals.ensureChunk}(ids[${chunksStartPosition}])`;
+ ? `Promise.all(ids.slice(${chunksStartPosition}).map(${RuntimeGlobals.ensureChunk}))`
+ : `${RuntimeGlobals.ensureChunk}(ids[${chunksStartPosition}])`;
const returnModuleObject = this.getReturnModuleObjectSource(
fakeMap,
true,
diff --git a/lib/ContextModuleFactory.js b/lib/ContextModuleFactory.js
index b30447b8788..65a2131bc69 100644
--- a/lib/ContextModuleFactory.js
+++ b/lib/ContextModuleFactory.js
@@ -160,7 +160,7 @@ module.exports = class ContextModuleFactory extends ModuleFactory {
resolveOptions || EMPTY_RESOLVE_OPTIONS,
"dependencyType",
dependencies[0].category
- )
+ )
: resolveOptions
);
const loaderResolver = this.resolverFactory.get("loader");
diff --git a/lib/DefinePlugin.js b/lib/DefinePlugin.js
index f604523ecd2..ed02a3cbd2d 100644
--- a/lib/DefinePlugin.js
+++ b/lib/DefinePlugin.js
@@ -23,9 +23,11 @@ const createHash = require("./util/createHash");
/** @typedef {import("estree").Expression} Expression */
/** @typedef {import("./Compiler")} Compiler */
+/** @typedef {import("./Module").BuildInfo} BuildInfo */
/** @typedef {import("./NormalModule")} NormalModule */
/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */
+/** @typedef {import("./javascript/JavascriptParser").Range} Range */
/** @typedef {import("./logging/Logger").Logger} Logger */
/** @typedef {null|undefined|RegExp|Function|string|number|boolean|bigint|undefined} CodeValuePrimitive */
@@ -66,7 +68,7 @@ class RuntimeValue {
* @returns {CodeValuePrimitive} code
*/
exec(parser, valueCacheVersions, key) {
- const buildInfo = parser.state.module.buildInfo;
+ const buildInfo = /** @type {BuildInfo} */ (parser.state.module.buildInfo);
if (this.options === true) {
buildInfo.cacheable = false;
} else {
@@ -136,19 +138,21 @@ const stringifyObj = (
let code;
let arr = Array.isArray(obj);
if (arr) {
- code = `[${obj
- .map(code =>
- toCode(
- code,
- parser,
- valueCacheVersions,
- key,
- runtimeTemplate,
- logger,
- null
+ code = `[${
+ /** @type {any[]} */ (obj)
+ .map(code =>
+ toCode(
+ code,
+ parser,
+ valueCacheVersions,
+ key,
+ runtimeTemplate,
+ logger,
+ null
+ )
)
- )
- .join(",")}]`;
+ .join(",")
+ }]`;
} else {
let keys = Object.keys(obj);
if (objKeys) {
@@ -157,7 +161,7 @@ const stringifyObj = (
}
code = `{${keys
.map(key => {
- const code = obj[key];
+ const code = /** @type {{[k: string]: any}} */ (obj)[key];
return (
JSON.stringify(key) +
":" +
@@ -263,6 +267,10 @@ const toCode = (
return strCode;
};
+/**
+ * @param {CodeValue} code code
+ * @returns {string | undefined} result
+ */
const toCacheVersion = code => {
if (code === null) {
return "null";
@@ -285,7 +293,7 @@ const toCacheVersion = code => {
if (typeof code === "object") {
const items = Object.keys(code).map(key => ({
key,
- value: toCacheVersion(code[key])
+ value: toCacheVersion(/** @type {Record} */ (code)[key])
}));
if (items.some(({ value }) => value === undefined)) return undefined;
return `{${items.map(({ key, value }) => `${key}: ${value}`).join(", ")}}`;
@@ -353,14 +361,21 @@ class DefinePlugin {
const handler = parser => {
const mainValue = compilation.valueCacheVersions.get(VALUE_DEP_MAIN);
parser.hooks.program.tap(PLUGIN_NAME, () => {
- const { buildInfo } = parser.state.module;
+ const buildInfo = /** @type {BuildInfo} */ (
+ parser.state.module.buildInfo
+ );
if (!buildInfo.valueDependencies)
buildInfo.valueDependencies = new Map();
buildInfo.valueDependencies.set(VALUE_DEP_MAIN, mainValue);
});
+ /**
+ * @param {string} key key
+ */
const addValueDependency = key => {
- const { buildInfo } = parser.state.module;
+ const buildInfo = /** @type {BuildInfo} */ (
+ parser.state.module.buildInfo
+ );
buildInfo.valueDependencies.set(
VALUE_DEP_PREFIX + key,
compilation.valueCacheVersions.get(VALUE_DEP_PREFIX + key)
@@ -376,7 +391,7 @@ class DefinePlugin {
/**
* Walk definitions
- * @param {Object} definitions Definitions map
+ * @param {Record} definitions Definitions map
* @param {string} prefix Prefix string
* @returns {void}
*/
@@ -389,7 +404,10 @@ class DefinePlugin {
!(code instanceof RuntimeValue) &&
!(code instanceof RegExp)
) {
- walkDefinitions(code, prefix + key + ".");
+ walkDefinitions(
+ /** @type {Record} */ (code),
+ prefix + key + "."
+ );
applyObjectDefine(prefix + key, code);
return;
}
@@ -458,7 +476,7 @@ class DefinePlugin {
)
);
recurse = false;
- res.setRange(expr.range);
+ res.setRange(/** @type {Range} */ (expr.range));
return res;
});
parser.hooks.expression.for(key).tap(PLUGIN_NAME, expr => {
@@ -470,7 +488,7 @@ class DefinePlugin {
originalKey,
runtimeTemplate,
logger,
- !parser.isAsiPosition(expr.range[0]),
+ !parser.isAsiPosition(/** @type {Range} */ (expr.range)[0]),
parser.destructuringAssignmentPropertiesFor(expr)
);
@@ -517,7 +535,7 @@ class DefinePlugin {
: "typeof (" + codeCode + ")";
const res = parser.evaluate(typeofCode);
recurseTypeof = false;
- res.setRange(expr.range);
+ res.setRange(/** @type {Range} */ (expr.range));
return res;
});
parser.hooks.typeof.for(key).tap(PLUGIN_NAME, expr => {
@@ -559,7 +577,7 @@ class DefinePlugin {
return new BasicEvaluatedExpression()
.setTruthy()
.setSideEffects(false)
- .setRange(expr.range);
+ .setRange(/** @type {Range} */ (expr.range));
});
parser.hooks.evaluateTypeof
.for(key)
@@ -576,7 +594,7 @@ class DefinePlugin {
key,
runtimeTemplate,
logger,
- !parser.isAsiPosition(expr.range[0]),
+ !parser.isAsiPosition(/** @type {Range} */ (expr.range)[0]),
parser.destructuringAssignmentPropertiesFor(expr)
);
@@ -622,7 +640,7 @@ class DefinePlugin {
/**
* Walk definitions
- * @param {Object} definitions Definitions map
+ * @param {Record} definitions Definitions map
* @param {string} prefix Prefix string
* @returns {void}
*/
@@ -649,7 +667,10 @@ class DefinePlugin {
!(code instanceof RuntimeValue) &&
!(code instanceof RegExp)
) {
- walkDefinitionsForValues(code, prefix + key + ".");
+ walkDefinitionsForValues(
+ /** @type {Record} */ (code),
+ prefix + key + "."
+ );
}
});
};
diff --git a/lib/DependencyTemplate.js b/lib/DependencyTemplate.js
index 67a4d7b8305..b568d0c0ebe 100644
--- a/lib/DependencyTemplate.js
+++ b/lib/DependencyTemplate.js
@@ -26,10 +26,12 @@
* @property {ChunkGraph} chunkGraph the chunk graph
* @property {Set} runtimeRequirements the requirements for runtime
* @property {Module} module current module
- * @property {RuntimeSpec} runtime current runtimes, for which code is generated
+ * @property {RuntimeSpec} runtime current runtime, for which code is generated
+ * @property {RuntimeSpec[]} [runtimes] current runtimes, for which code is generated
* @property {InitFragment[]} initFragments mutable array of init fragments for the current module
* @property {ConcatenationScope=} concatenationScope when in a concatenated module, information about other concatenated modules
* @property {CodeGenerationResults} codeGenerationResults the code generation results
+ * @property {InitFragment[]} chunkInitFragments chunkInitFragments
*/
/**
diff --git a/lib/EnvironmentNotSupportAsyncWarning.js b/lib/EnvironmentNotSupportAsyncWarning.js
new file mode 100644
index 00000000000..1a1ea9ece66
--- /dev/null
+++ b/lib/EnvironmentNotSupportAsyncWarning.js
@@ -0,0 +1,52 @@
+/*
+ MIT License http://www.opensource.org/licenses/mit-license.php
+ Author Gengkun He @ahabhgk
+*/
+
+"use strict";
+
+const WebpackError = require("./WebpackError");
+const makeSerializable = require("./util/makeSerializable");
+
+/** @typedef {import("./Module")} Module */
+/** @typedef {import("./Compilation")} Compilation */
+/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
+/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
+/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
+/** @typedef {"asyncWebAssembly" | "topLevelAwait" | "external promise" | "external script" | "external import" | "external module"} Feature */
+
+class EnvironmentNotSupportAsyncWarning extends WebpackError {
+ /**
+ * Creates an instance of EnvironmentNotSupportAsyncWarning.
+ * @param {Module} module module
+ * @param {Feature} feature feature
+ */
+ constructor(module, feature) {
+ const message = `The generated code contains 'async/await' because this module is using "${feature}".
+However, your target environment does not appear to support 'async/await'.
+As a result, the code may not run as expected or may cause runtime errors.`;
+ super(message);
+
+ this.name = "EnvironmentNotSupportAsyncWarning";
+ this.module = module;
+ }
+
+ /**
+ * Creates an instance of EnvironmentNotSupportAsyncWarning.
+ * @param {Module} module module
+ * @param {RuntimeTemplate} runtimeTemplate compilation
+ * @param {Feature} feature feature
+ */
+ static check(module, runtimeTemplate, feature) {
+ if (!runtimeTemplate.supportsAsyncFunction()) {
+ module.addWarning(new EnvironmentNotSupportAsyncWarning(module, feature));
+ }
+ }
+}
+
+makeSerializable(
+ EnvironmentNotSupportAsyncWarning,
+ "webpack/lib/EnvironmentNotSupportAsyncWarning"
+);
+
+module.exports = EnvironmentNotSupportAsyncWarning;
diff --git a/lib/EvalDevToolModulePlugin.js b/lib/EvalDevToolModulePlugin.js
index b0a47db88f7..003080806d5 100644
--- a/lib/EvalDevToolModulePlugin.js
+++ b/lib/EvalDevToolModulePlugin.js
@@ -82,7 +82,7 @@ class EvalDevToolModulePlugin {
compilation.outputOptions.trustedTypes
? `${RuntimeGlobals.createScript}(${JSON.stringify(
content + footer
- )})`
+ )})`
: JSON.stringify(content + footer)
});`
);
diff --git a/lib/EvalSourceMapDevToolPlugin.js b/lib/EvalSourceMapDevToolPlugin.js
index b3803b11ddb..4ef3dc28c57 100644
--- a/lib/EvalSourceMapDevToolPlugin.js
+++ b/lib/EvalSourceMapDevToolPlugin.js
@@ -129,7 +129,7 @@ class EvalSourceMapDevToolPlugin {
// Clone (flat) the sourcemap to ensure that the mutations below do not persist.
sourceMap = { ...sourceMap };
- const context = compiler.options.context;
+ const context = /** @type {string} */ (compiler.options.context);
const root = compiler.root;
const modules = sourceMap.sources.map(source => {
if (!source.startsWith("webpack://")) return source;
@@ -182,7 +182,7 @@ class EvalSourceMapDevToolPlugin {
compilation.outputOptions.trustedTypes
? `${RuntimeGlobals.createScript}(${JSON.stringify(
content + footer
- )})`
+ )})`
: JSON.stringify(content + footer)
});`
)
diff --git a/lib/ExportsInfoApiPlugin.js b/lib/ExportsInfoApiPlugin.js
index 5d469f6bfe9..faf4594bbd0 100644
--- a/lib/ExportsInfoApiPlugin.js
+++ b/lib/ExportsInfoApiPlugin.js
@@ -48,12 +48,12 @@ class ExportsInfoApiPlugin {
/** @type {Range} */ (expr.range),
members.slice(0, -1),
members[members.length - 1]
- )
+ )
: new ExportsInfoDependency(
/** @type {Range} */ (expr.range),
null,
members[0]
- );
+ );
dep.loc = /** @type {DependencyLocation} */ (expr.loc);
parser.state.module.addDependency(dep);
return true;
diff --git a/lib/ExternalModule.js b/lib/ExternalModule.js
index 7f00a20a975..a8fb263bf0c 100644
--- a/lib/ExternalModule.js
+++ b/lib/ExternalModule.js
@@ -7,6 +7,7 @@
const { OriginalSource, RawSource } = require("webpack-sources");
const ConcatenationScope = require("./ConcatenationScope");
+const EnvironmentNotSupportAsyncWarning = require("./EnvironmentNotSupportAsyncWarning");
const { UsageState } = require("./ExportsInfo");
const InitFragment = require("./InitFragment");
const Module = require("./Module");
@@ -217,7 +218,12 @@ register(
}
);
-const generateModuleRemapping = (input, exportsInfo, runtime) => {
+const generateModuleRemapping = (
+ input,
+ exportsInfo,
+ runtime,
+ runtimeTemplate
+) => {
if (exportsInfo.otherExportsInfo.getUsed(runtime) === UsageState.Unused) {
const properties = [];
for (const exportInfo of exportsInfo.orderedExports) {
@@ -235,9 +241,9 @@ const generateModuleRemapping = (input, exportsInfo, runtime) => {
}
}
properties.push(
- `[${JSON.stringify(used)}]: () => ${input}${propertyAccess([
- exportInfo.name
- ])}`
+ `[${JSON.stringify(used)}]: ${runtimeTemplate.returningFunction(
+ `${input}${propertyAccess([exportInfo.name])}`
+ )}`
);
}
return `x({ ${properties.join(", ")} })`;
@@ -248,21 +254,21 @@ const generateModuleRemapping = (input, exportsInfo, runtime) => {
* @param {string|string[]} moduleAndSpecifiers the module request
* @param {ExportsInfo} exportsInfo exports info of this module
* @param {RuntimeSpec} runtime the runtime
- * @param {string | HashConstructor=} hashFunction the hash function to use
+ * @param {RuntimeTemplate} runtimeTemplate the runtime template
* @returns {SourceData} the generated source
*/
const getSourceForModuleExternal = (
moduleAndSpecifiers,
exportsInfo,
runtime,
- hashFunction
+ runtimeTemplate
) => {
if (!Array.isArray(moduleAndSpecifiers))
moduleAndSpecifiers = [moduleAndSpecifiers];
const initFragment = new ModuleExternalInitFragment(
moduleAndSpecifiers[0],
undefined,
- hashFunction
+ runtimeTemplate.outputOptions.hashFunction
);
const baseAccess = `${initFragment.getNamespaceIdentifier()}${propertyAccess(
moduleAndSpecifiers,
@@ -271,12 +277,19 @@ const getSourceForModuleExternal = (
const moduleRemapping = generateModuleRemapping(
baseAccess,
exportsInfo,
- runtime
+ runtime,
+ runtimeTemplate
);
let expression = moduleRemapping || baseAccess;
return {
expression,
- init: `var x = y => { var x = {}; ${RuntimeGlobals.definePropertyGetters}(x, y); return x; }\nvar y = x => () => x`,
+ init: `var x = ${runtimeTemplate.basicFunction(
+ "y",
+ `var x = {}; ${RuntimeGlobals.definePropertyGetters}(x, y); return x`
+ )} \nvar y = ${runtimeTemplate.returningFunction(
+ runtimeTemplate.returningFunction("x"),
+ "x"
+ )}`,
runtimeRequirements: moduleRemapping
? RUNTIME_REQUIREMENTS_FOR_MODULE
: undefined,
@@ -355,7 +368,7 @@ const getSourceForAmdOrUmdExternal = (
externalVariable,
Array.isArray(request) ? request.join(".") : request,
runtimeTemplate
- )
+ )
: undefined,
expression: externalVariable
};
@@ -491,6 +504,11 @@ class ExternalModule extends Module {
}
} else {
this.buildMeta.async = true;
+ EnvironmentNotSupportAsyncWarning.check(
+ this,
+ compilation.runtimeTemplate,
+ "external module"
+ );
if (!Array.isArray(request) || request.length === 1) {
this.buildMeta.exportsType = "namespace";
canMangle = false;
@@ -498,11 +516,28 @@ class ExternalModule extends Module {
}
break;
case "script":
+ this.buildMeta.async = true;
+ EnvironmentNotSupportAsyncWarning.check(
+ this,
+ compilation.runtimeTemplate,
+ "external script"
+ );
+ break;
case "promise":
this.buildMeta.async = true;
+ EnvironmentNotSupportAsyncWarning.check(
+ this,
+ compilation.runtimeTemplate,
+ "external promise"
+ );
break;
case "import":
this.buildMeta.async = true;
+ EnvironmentNotSupportAsyncWarning.check(
+ this,
+ compilation.runtimeTemplate,
+ "external import"
+ );
if (!Array.isArray(request) || request.length === 1) {
this.buildMeta.exportsType = "namespace";
canMangle = false;
@@ -569,7 +604,7 @@ class ExternalModule extends Module {
? getSourceForCommonJsExternalInNodeModule(
request,
runtimeTemplate.outputOptions.importMetaName
- )
+ )
: getSourceForCommonJsExternal(request);
case "amd":
case "amd-require":
@@ -610,7 +645,7 @@ class ExternalModule extends Module {
request,
moduleGraph.getExportsInfo(this),
runtime,
- runtimeTemplate.outputOptions.hashFunction
+ runtimeTemplate
);
}
case "var":
diff --git a/lib/ExternalModuleFactoryPlugin.js b/lib/ExternalModuleFactoryPlugin.js
index 5dae85c7184..bd917ba49b4 100644
--- a/lib/ExternalModuleFactoryPlugin.js
+++ b/lib/ExternalModuleFactoryPlugin.js
@@ -192,7 +192,7 @@ class ExternalModuleFactoryPlugin {
data.resolveOptions || EMPTY_RESOLVE_OPTIONS,
"dependencyType",
dependencyType
- )
+ )
: data.resolveOptions
);
if (options) resolver = resolver.withOptions(options);
diff --git a/lib/FileSystemInfo.js b/lib/FileSystemInfo.js
index df01c158c12..59bf473368c 100644
--- a/lib/FileSystemInfo.js
+++ b/lib/FileSystemInfo.js
@@ -729,7 +729,8 @@ class SnapshotOptimization {
}
const parseString = str => {
- if (str[0] === "'") str = `"${str.slice(1, -1).replace(/"/g, '\\"')}"`;
+ if (str[0] === "'" || str[0] === "`")
+ str = `"${str.slice(1, -1).replace(/"/g, '\\"')}"`;
return JSON.parse(str);
};
@@ -898,6 +899,7 @@ class FileSystemInfo {
/**
* @param {InputFileSystem} fs file system
* @param {Object} options options
+ * @param {Iterable=} options.unmanagedPaths paths that are not managed by a package manager and the contents are subject to change
* @param {Iterable=} options.managedPaths paths that are only managed by a package manager
* @param {Iterable=} options.immutablePaths paths that are immutable
* @param {Logger=} options.logger logger used to log invalid snapshots
@@ -906,6 +908,7 @@ class FileSystemInfo {
constructor(
fs,
{
+ unmanagedPaths = [],
managedPaths = [],
immutablePaths = [],
logger,
@@ -1040,6 +1043,14 @@ class FileSystemInfo {
parallelism: 10,
processor: this._getManagedItemDirectoryInfo.bind(this)
});
+ const _unmanagedPaths = Array.from(unmanagedPaths);
+ this.unmanagedPathsWithSlash = /** @type {string[]} */ (
+ _unmanagedPaths.filter(p => typeof p === "string")
+ ).map(p => join(fs, p, "_").slice(0, -1));
+ this.unmanagedPathsRegExps = /** @type {RegExp[]} */ (
+ _unmanagedPaths.filter(p => typeof p !== "string")
+ );
+
this.managedPaths = Array.from(managedPaths);
this.managedPathsWithSlash = /** @type {string[]} */ (
this.managedPaths.filter(p => typeof p === "string")
@@ -1733,7 +1744,7 @@ class FileSystemInfo {
type: RBDT_RESOLVE_ESM_FILE,
context,
path: dependency,
- expected: undefined,
+ expected: imp.d > -1 ? false : undefined,
issuer: job
});
} catch (e) {
@@ -2028,6 +2039,12 @@ class FileSystemInfo {
}
};
const checkManaged = (path, managedSet) => {
+ for (const unmanagedPath of this.unmanagedPathsRegExps) {
+ if (unmanagedPath.test(path)) return false;
+ }
+ for (const unmanagedPath of this.unmanagedPathsWithSlash) {
+ if (path.startsWith(unmanagedPath)) return false;
+ }
for (const immutablePath of this.immutablePathsRegExps) {
if (immutablePath.test(path)) {
managedSet.add(path);
@@ -3346,7 +3363,7 @@ class FileSystemInfo {
: {
...timestamp,
...hash
- };
+ };
this._contextTshs.set(path, result);
callback(null, result);
};
diff --git a/lib/FlagDependencyExportsPlugin.js b/lib/FlagDependencyExportsPlugin.js
index defbf3781a8..9befc25447a 100644
--- a/lib/FlagDependencyExportsPlugin.js
+++ b/lib/FlagDependencyExportsPlugin.js
@@ -246,7 +246,7 @@ class FlagDependencyExportsPlugin {
from,
fromExport === undefined ? [name] : fromExport,
priority
- ))
+ ))
) {
changed = true;
}
diff --git a/lib/Generator.js b/lib/Generator.js
index ffa93230ac4..76099c44e77 100644
--- a/lib/Generator.js
+++ b/lib/Generator.js
@@ -27,6 +27,7 @@
* @property {ChunkGraph} chunkGraph the chunk graph
* @property {Set} runtimeRequirements the requirements for runtime
* @property {RuntimeSpec} runtime the runtime
+ * @property {RuntimeSpec[]} [runtimes] the runtimes
* @property {ConcatenationScope=} concatenationScope when in concatenated module, information about other concatenated modules
* @property {CodeGenerationResults=} codeGenerationResults code generation results of other modules (need to have a codeGenerationDependency to use that)
* @property {string} type which kind of code should be generated
diff --git a/lib/HotModuleReplacementPlugin.js b/lib/HotModuleReplacementPlugin.js
index 9e117403c68..6a8eb98e10d 100644
--- a/lib/HotModuleReplacementPlugin.js
+++ b/lib/HotModuleReplacementPlugin.js
@@ -447,7 +447,7 @@ class HotModuleReplacementPlugin {
: compilation.codeGenerationResults.getHash(
module,
chunk.runtime
- );
+ );
if (records.chunkModuleHashes[key] !== hash) {
updatedModules.add(module, chunk);
}
@@ -571,7 +571,7 @@ class HotModuleReplacementPlugin {
: compilation.codeGenerationResults.getHash(
module,
newRuntime
- );
+ );
if (hash !== oldHash) {
if (module.type === WEBPACK_MODULE_TYPE_RUNTIME) {
newRuntimeModules = newRuntimeModules || [];
@@ -735,7 +735,7 @@ To fix this, make sure to include [runtime] in the output.hotUpdateMainFilename
Array.from(removedModules, m =>
chunkGraph.getModuleId(m)
)
- )
+ )
};
const source = new RawSource(JSON.stringify(hotUpdateMainJson));
diff --git a/lib/InitFragment.js b/lib/InitFragment.js
index 415660b5d34..5440670d9de 100644
--- a/lib/InitFragment.js
+++ b/lib/InitFragment.js
@@ -36,15 +36,15 @@ const sortFragmentWithIndex = ([a, i], [b, j]) => {
};
/**
- * @template Context
+ * @template GenerateContext
*/
class InitFragment {
/**
- * @param {string|Source} content the source code that will be included as initialization code
+ * @param {string | Source} content the source code that will be included as initialization code
* @param {number} stage category of initialization code (contribute to order)
* @param {number} position position in the category (contribute to order)
* @param {string=} key unique key to avoid emitting the same initialization code twice
- * @param {string|Source=} endContent the source code that will be included at the end of the module
+ * @param {string | Source=} endContent the source code that will be included at the end of the module
*/
constructor(content, stage, position, key, endContent) {
this.content = content;
@@ -55,15 +55,15 @@ class InitFragment {
}
/**
- * @param {Context} context context
- * @returns {string|Source} the source code that will be included as initialization code
+ * @param {GenerateContext} context context
+ * @returns {string | Source} the source code that will be included as initialization code
*/
getContent(context) {
return this.content;
}
/**
- * @param {Context} context context
+ * @param {GenerateContext} context context
* @returns {string|Source=} the source code that will be included at the end of the module
*/
getEndContent(context) {
@@ -91,7 +91,7 @@ class InitFragment {
for (const [fragment] of sortedFragments) {
if (
typeof (
- /** @type {InitFragment & { mergeAll?: (fragments: InitFragment[]) => InitFragment[] }} */
+ /** @type {InitFragment & { mergeAll?: (fragments: InitFragment[]) => InitFragment[] }} */
(fragment).mergeAll
) === "function"
) {
diff --git a/lib/LibManifestPlugin.js b/lib/LibManifestPlugin.js
index 32939ed46d6..e3d5c3ec3f5 100644
--- a/lib/LibManifestPlugin.js
+++ b/lib/LibManifestPlugin.js
@@ -46,7 +46,10 @@ class LibManifestPlugin {
*/
apply(compiler) {
compiler.hooks.emit.tapAsync(
- "LibManifestPlugin",
+ {
+ name: "LibManifestPlugin",
+ stage: 110
+ },
(compilation, callback) => {
const moduleGraph = compilation.moduleGraph;
asyncLib.forEach(
diff --git a/lib/Module.js b/lib/Module.js
index 7d8ebf4dcd3..5f05a848545 100644
--- a/lib/Module.js
+++ b/lib/Module.js
@@ -59,7 +59,8 @@ const makeSerializable = require("./util/makeSerializable");
* @property {RuntimeTemplate} runtimeTemplate the runtime template
* @property {ModuleGraph} moduleGraph the module graph
* @property {ChunkGraph} chunkGraph the chunk graph
- * @property {RuntimeSpec} runtime the runtimes code should be generated for
+ * @property {RuntimeSpec} runtime the runtime code should be generated for
+ * @property {RuntimeSpec[]} [runtimes] the runtimes code should be generated for
* @property {ConcatenationScope=} concatenationScope when in concatenated module, information about other concatenated modules
* @property {CodeGenerationResults} codeGenerationResults code generation results of other modules (need to have a codeGenerationDependency to use that)
* @property {Compilation=} compilation the compilation
diff --git a/lib/ModuleFilenameHelpers.js b/lib/ModuleFilenameHelpers.js
index 236c7ec8df8..949a011ee21 100644
--- a/lib/ModuleFilenameHelpers.js
+++ b/lib/ModuleFilenameHelpers.js
@@ -162,7 +162,7 @@ ModuleFilenameHelpers.createFilename = (
? options
: {
moduleFilenameTemplate: options
- })
+ })
};
let absoluteResourcePath;
diff --git a/lib/ModuleInfoHeaderPlugin.js b/lib/ModuleInfoHeaderPlugin.js
index 2ee0b2a8122..0ed0f2527aa 100644
--- a/lib/ModuleInfoHeaderPlugin.js
+++ b/lib/ModuleInfoHeaderPlugin.js
@@ -96,7 +96,7 @@ const printExportsInfoToSource = (
.map(e => JSON.stringify(e).slice(1, -1))
.join(".")}`
: ""
- }`
+ }`
: ""
}`
) + "\n"
diff --git a/lib/MultiStats.js b/lib/MultiStats.js
index d236aef43f4..4f443bdb42b 100644
--- a/lib/MultiStats.js
+++ b/lib/MultiStats.js
@@ -59,8 +59,8 @@ class MultiStats {
...(typeof childOptions === "string"
? { preset: childOptions }
: childOptions && typeof childOptions === "object"
- ? childOptions
- : undefined)
+ ? childOptions
+ : undefined)
},
context
);
diff --git a/lib/NodeStuffPlugin.js b/lib/NodeStuffPlugin.js
index 4f288068666..e11d452ab01 100644
--- a/lib/NodeStuffPlugin.js
+++ b/lib/NodeStuffPlugin.js
@@ -13,6 +13,7 @@ const NodeStuffInWebError = require("./NodeStuffInWebError");
const RuntimeGlobals = require("./RuntimeGlobals");
const CachedConstDependency = require("./dependencies/CachedConstDependency");
const ConstDependency = require("./dependencies/ConstDependency");
+const ExternalModuleDependency = require("./dependencies/ExternalModuleDependency");
const {
evaluateToString,
expressionIsUnsupported
@@ -52,6 +53,11 @@ class NodeStuffPlugin {
compiler.hooks.compilation.tap(
PLUGIN_NAME,
(compilation, { normalModuleFactory }) => {
+ compilation.dependencyTemplates.set(
+ ExternalModuleDependency,
+ new ExternalModuleDependency.Template()
+ );
+
/**
* @param {JavascriptParser} parser the parser
* @param {JavascriptParserOptions} parserOptions options
@@ -128,6 +134,35 @@ class NodeStuffPlugin {
});
};
+ /**
+ * @param {string} expressionName expression name
+ * @param {(value: string) => string} fn function
+ * @returns {void}
+ */
+ const setUrlModuleConstant = (expressionName, fn) => {
+ parser.hooks.expression
+ .for(expressionName)
+ .tap(PLUGIN_NAME, expr => {
+ const dep = new ExternalModuleDependency(
+ "url",
+ [
+ {
+ name: "fileURLToPath",
+ value: "__webpack_fileURLToPath__"
+ }
+ ],
+ undefined,
+ fn("__webpack_fileURLToPath__"),
+ /** @type {Range} */ (expr.range),
+ expressionName
+ );
+ dep.loc = /** @type {DependencyLocation} */ (expr.loc);
+ parser.state.module.addPresentationalDependency(dep);
+
+ return true;
+ });
+ };
+
/**
* @param {string} expressionName expression name
* @param {string} value value
@@ -150,6 +185,12 @@ class NodeStuffPlugin {
"__filename is a Node.js feature and isn't available in browsers."
);
break;
+ case "node-module":
+ setUrlModuleConstant(
+ "__filename",
+ functionName => `${functionName}(import.meta.url)`
+ );
+ break;
case true:
setModuleConstant("__filename", module =>
relative(compiler.inputFileSystem, context, module.resource)
@@ -177,6 +218,13 @@ class NodeStuffPlugin {
"__dirname is a Node.js feature and isn't available in browsers."
);
break;
+ case "node-module":
+ setUrlModuleConstant(
+ "__dirname",
+ functionName =>
+ `${functionName}(import.meta.url + "/..").slice(0, -1)`
+ );
+ break;
case true:
setModuleConstant("__dirname", module =>
relative(compiler.inputFileSystem, context, module.context)
diff --git a/lib/NormalModule.js b/lib/NormalModule.js
index 87b78f30f06..fa0cc1fac1f 100644
--- a/lib/NormalModule.js
+++ b/lib/NormalModule.js
@@ -132,14 +132,14 @@ const contextifySourceMap = (context, sourceMap, associatedObjectForCache) => {
const mapper = !sourceRoot
? source => source
: sourceRoot.endsWith("/")
- ? source =>
- source.startsWith("/")
- ? `${sourceRoot.slice(0, -1)}${source}`
- : `${sourceRoot}${source}`
- : source =>
- source.startsWith("/")
- ? `${sourceRoot}${source}`
- : `${sourceRoot}/${source}`;
+ ? source =>
+ source.startsWith("/")
+ ? `${sourceRoot.slice(0, -1)}${source}`
+ : `${sourceRoot}${source}`
+ : source =>
+ source.startsWith("/")
+ ? `${sourceRoot}${source}`
+ : `${sourceRoot}/${source}`;
const newSources = sourceMap.sources.map(source =>
contextifySourceUrl(context, mapper(source), associatedObjectForCache)
);
@@ -782,7 +782,7 @@ class NormalModule extends Module {
currentLoader
? compilation.runtimeTemplate.requestShortener.shorten(
currentLoader.loader
- )
+ )
: "unknown"
}) didn't return a Buffer or String`
);
@@ -1181,6 +1181,7 @@ class NormalModule extends Module {
moduleGraph,
chunkGraph,
runtime,
+ runtimes,
concatenationScope,
codeGenerationResults,
sourceTypes
@@ -1204,7 +1205,7 @@ class NormalModule extends Module {
const source = this.error
? new RawSource(
"throw new Error(" + JSON.stringify(this.error.message) + ");"
- )
+ )
: this.generator.generate(this, {
dependencyTemplates,
runtimeTemplate,
@@ -1212,11 +1213,12 @@ class NormalModule extends Module {
chunkGraph,
runtimeRequirements,
runtime,
+ runtimes,
concatenationScope,
codeGenerationResults,
getData,
type
- });
+ });
if (source) {
sources.set(type, new CachedSource(source));
diff --git a/lib/NormalModuleFactory.js b/lib/NormalModuleFactory.js
index a0d8b767f2f..9b28c778c38 100644
--- a/lib/NormalModuleFactory.js
+++ b/lib/NormalModuleFactory.js
@@ -411,8 +411,8 @@ class NormalModuleFactory extends ModuleFactory {
noPreAutoLoaders || noPrePostAutoLoaders
? 2
: noAutoLoaders
- ? 1
- : 0
+ ? 1
+ : 0
)
.split(/!+/);
unresolvedResource = rawElements.pop();
@@ -676,7 +676,7 @@ class NormalModuleFactory extends ModuleFactory {
resolveOptions || EMPTY_RESOLVE_OPTIONS,
"dependencyType",
dependencyType
- )
+ )
: resolveOptions
);
this.resolveResource(
@@ -1063,10 +1063,10 @@ If changing the source code is not an option there is also a resolve options cal
const type = /\.mjs$/i.test(parsedResult.path)
? "module"
: /\.cjs$/i.test(parsedResult.path)
- ? "commonjs"
- : resolveRequest.descriptionFileData === undefined
- ? undefined
- : resolveRequest.descriptionFileData.type;
+ ? "commonjs"
+ : resolveRequest.descriptionFileData === undefined
+ ? undefined
+ : resolveRequest.descriptionFileData.type;
const resolved = {
loader: parsedResult.path,
diff --git a/lib/RuntimeTemplate.js b/lib/RuntimeTemplate.js
index e4b6a141c7b..692ded112c5 100644
--- a/lib/RuntimeTemplate.js
+++ b/lib/RuntimeTemplate.js
@@ -102,6 +102,10 @@ class RuntimeTemplate {
return this.outputOptions.environment.arrowFunction;
}
+ supportsAsyncFunction() {
+ return this.outputOptions.environment.asyncFunction;
+ }
+
supportsOptionalChaining() {
return this.outputOptions.environment.optionalChaining;
}
@@ -222,7 +226,7 @@ class RuntimeTemplate {
? `var [${items.join(", ")}] = ${value};`
: Template.asString(
items.map((item, i) => `var ${item} = ${value}[${i}];`)
- );
+ );
}
destructureObject(items, value) {
@@ -230,7 +234,7 @@ class RuntimeTemplate {
? `var {${items.join(", ")}} = ${value};`
: Template.asString(
items.map(item => `var ${item} = ${value}${propertyAccess([item])};`)
- );
+ );
}
iife(args, body) {
@@ -242,7 +246,7 @@ class RuntimeTemplate {
? `for(const ${variable} of ${array}) {\n${Template.indent(body)}\n}`
: `${array}.forEach(function(${variable}) {\n${Template.indent(
body
- )}\n});`;
+ )}\n});`;
}
/**
@@ -343,10 +347,10 @@ class RuntimeTemplate {
moduleId === null
? JSON.stringify("Module is not available (weak dependency)")
: idExpr
- ? `"Module '" + ${idExpr} + "' is not available (weak dependency)"`
- : JSON.stringify(
- `Module '${moduleId}' is not available (weak dependency)`
- );
+ ? `"Module '" + ${idExpr} + "' is not available (weak dependency)"`
+ : JSON.stringify(
+ `Module '${moduleId}' is not available (weak dependency)`
+ );
const comment = request ? Template.toNormalComment(request) + " " : "";
const errorStatements =
`var e = new Error(${errorMessage}); ` +
@@ -840,8 +844,8 @@ class RuntimeTemplate {
return asiSafe
? `(${importVar}_default()${propertyAccess(exportName, 1)})`
: asiSafe === false
- ? `;(${importVar}_default()${propertyAccess(exportName, 1)})`
- : `${importVar}_default.a${propertyAccess(exportName, 1)}`;
+ ? `;(${importVar}_default()${propertyAccess(exportName, 1)})`
+ : `${importVar}_default.a${propertyAccess(exportName, 1)}`;
}
case "default-only":
case "default-with-named":
@@ -898,8 +902,8 @@ class RuntimeTemplate {
return asiSafe
? `(0,${access})`
: asiSafe === false
- ? `;(0,${access})`
- : `/*#__PURE__*/Object(${access})`;
+ ? `;(0,${access})`
+ : `/*#__PURE__*/Object(${access})`;
}
return access;
} else {
diff --git a/lib/SourceMapDevToolPlugin.js b/lib/SourceMapDevToolPlugin.js
index 2bbad9ca88e..608fe302463 100644
--- a/lib/SourceMapDevToolPlugin.js
+++ b/lib/SourceMapDevToolPlugin.js
@@ -486,7 +486,7 @@ class SourceMapDevToolPlugin {
outputFs,
`/${options.fileContext}`,
`/${filename}`
- )
+ )
: filename,
contentHash: sourceMapContentHash
};
@@ -501,7 +501,7 @@ class SourceMapDevToolPlugin {
outputFs,
dirname(outputFs, `/${file}`),
`/${sourceMapFile}`
- );
+ );
/** @type {Source} */
let asset = new RawSource(source);
if (currentSourceMappingURLComment !== false) {
diff --git a/lib/Stats.js b/lib/Stats.js
index 567683b7bd7..efb4d95ba7b 100644
--- a/lib/Stats.js
+++ b/lib/Stats.js
@@ -65,6 +65,10 @@ class Stats {
});
}
+ /**
+ * @param {(string|StatsOptions)=} options stats options
+ * @returns {string} string output
+ */
toString(options) {
options = this.compilation.createStatsOptions(options, {
forToString: true
diff --git a/lib/WebpackOptionsApply.js b/lib/WebpackOptionsApply.js
index b5a4867de96..4ba16055767 100644
--- a/lib/WebpackOptionsApply.js
+++ b/lib/WebpackOptionsApply.js
@@ -307,7 +307,7 @@ class WebpackOptionsApply extends OptionsApply {
if (options.experiments.css) {
const CssModulesPlugin = require("./css/CssModulesPlugin");
- new CssModulesPlugin(options.experiments.css).apply(compiler);
+ new CssModulesPlugin().apply(compiler);
}
if (options.experiments.lazyCompilation) {
@@ -329,7 +329,7 @@ class WebpackOptionsApply extends OptionsApply {
options.externalsPresets.node ? "node" : "web"
}.js`
)
- }),
+ }),
entries: !lazyOptions || lazyOptions.entries !== false,
imports: !lazyOptions || lazyOptions.imports !== false,
test: (lazyOptions && lazyOptions.test) || undefined
@@ -588,7 +588,8 @@ class WebpackOptionsApply extends OptionsApply {
const AddManagedPathsPlugin = require("./cache/AddManagedPathsPlugin");
new AddManagedPathsPlugin(
options.snapshot.managedPaths,
- options.snapshot.immutablePaths
+ options.snapshot.immutablePaths,
+ options.snapshot.unmanagedPaths
).apply(compiler);
if (options.cache && typeof options.cache === "object") {
diff --git a/lib/asset/AssetModulesPlugin.js b/lib/asset/AssetModulesPlugin.js
index 9ab0157b6c9..f77fc82885b 100644
--- a/lib/asset/AssetModulesPlugin.js
+++ b/lib/asset/AssetModulesPlugin.js
@@ -208,9 +208,8 @@ class AssetModulesPlugin {
codeGenResult.data.get("fullContentHash")
});
} catch (e) {
- /** @type {Error} */ (
- e
- ).message += `\nduring rendering of asset ${module.identifier()}`;
+ /** @type {Error} */ (e).message +=
+ `\nduring rendering of asset ${module.identifier()}`;
throw e;
}
}
diff --git a/lib/async-modules/AwaitDependenciesInitFragment.js b/lib/async-modules/AwaitDependenciesInitFragment.js
index 2bec90769bd..7a991ab5aa4 100644
--- a/lib/async-modules/AwaitDependenciesInitFragment.js
+++ b/lib/async-modules/AwaitDependenciesInitFragment.js
@@ -42,8 +42,8 @@ class AwaitDependenciesInitFragment extends InitFragment {
}
/**
- * @param {Context} context context
- * @returns {string|Source} the source code that will be included as initialization code
+ * @param {GenerateContext} context context
+ * @returns {string | Source} the source code that will be included as initialization code
*/
getContent({ runtimeRequirements }) {
runtimeRequirements.add(RuntimeGlobals.module);
diff --git a/lib/buildChunkGraph.js b/lib/buildChunkGraph.js
index a484b844997..3e2a673fb97 100644
--- a/lib/buildChunkGraph.js
+++ b/lib/buildChunkGraph.js
@@ -266,12 +266,18 @@ const visitModules = (
/** @type {Map} */
const blockChunkGroups = new Map();
+ /** @type {Map} */
+ const blockByChunkGroups = new Map();
+
/** @type {Map} */
const namedChunkGroups = new Map();
/** @type {Map} */
const namedAsyncEntrypoints = new Map();
+ /** @type {Set} */
+ const outdatedOrderIndexChunkGroups = new Set();
+
const ADD_AND_ENTER_ENTRY_MODULE = 0;
const ADD_AND_ENTER_MODULE = 1;
const ENTER_MODULE = 2;
@@ -524,6 +530,7 @@ const visitModules = (
blockConnections.set(b, []);
}
blockChunkGroups.set(b, /** @type {ChunkGroupInfo} */ (cgi));
+ blockByChunkGroups.set(cgi, b);
} else if (entryOptions) {
entrypoint = /** @type {Entrypoint} */ (cgi.chunkGroup);
} else {
@@ -1208,6 +1215,7 @@ const visitModules = (
chunkGroupsForCombining.add(cgi);
}
}
+ outdatedOrderIndexChunkGroups.add(info);
}
outdatedChunkGroupInfo.clear();
};
@@ -1254,6 +1262,51 @@ const visitModules = (
}
}
+ for (const info of outdatedOrderIndexChunkGroups) {
+ const { chunkGroup, runtime } = info;
+
+ const block = blockByChunkGroups.get(info);
+
+ if (!block) {
+ continue;
+ }
+
+ let preOrderIndex = 0;
+ let postOrderIndex = 0;
+
+ const process = (current, visited = new Set()) => {
+ if (visited.has(current)) {
+ return;
+ }
+
+ visited.add(current);
+
+ const blockModules = getBlockModules(current, runtime);
+ if (blockModules === undefined) {
+ return;
+ }
+
+ for (let i = 0; i < blockModules.length; i += 2) {
+ const refModule = /** @type {Module} */ (blockModules[i]);
+ const activeState = /** @type {ConnectionState} */ (
+ blockModules[i + 1]
+ );
+ if (activeState === false) {
+ continue;
+ }
+
+ if (refModule) {
+ chunkGroup.setModulePreOrderIndex(refModule, preOrderIndex++);
+ process(refModule, visited);
+ chunkGroup.setModulePostOrderIndex(refModule, postOrderIndex++);
+ }
+ }
+ };
+
+ process(block);
+ }
+ outdatedOrderIndexChunkGroups.clear();
+
logger.log(
`${statProcessedQueueItems} queue items processed (${statProcessedBlocks} blocks)`
);
diff --git a/lib/cache/AddManagedPathsPlugin.js b/lib/cache/AddManagedPathsPlugin.js
index 702aa6c6b0b..d8e860f5272 100644
--- a/lib/cache/AddManagedPathsPlugin.js
+++ b/lib/cache/AddManagedPathsPlugin.js
@@ -11,10 +11,12 @@ class AddManagedPathsPlugin {
/**
* @param {Iterable} managedPaths list of managed paths
* @param {Iterable} immutablePaths list of immutable paths
+ * @param {Iterable} unmanagedPaths list of unmanaged paths
*/
- constructor(managedPaths, immutablePaths) {
+ constructor(managedPaths, immutablePaths, unmanagedPaths) {
this.managedPaths = new Set(managedPaths);
this.immutablePaths = new Set(immutablePaths);
+ this.unmanagedPaths = new Set(unmanagedPaths);
}
/**
@@ -29,6 +31,9 @@ class AddManagedPathsPlugin {
for (const immutablePath of this.immutablePaths) {
compiler.immutablePaths.add(immutablePath);
}
+ for (const unmanagedPath of this.unmanagedPaths) {
+ compiler.unmanagedPaths.add(unmanagedPath);
+ }
}
}
diff --git a/lib/cache/IdleFileCachePlugin.js b/lib/cache/IdleFileCachePlugin.js
index 8a82644fe29..2f913331c61 100644
--- a/lib/cache/IdleFileCachePlugin.js
+++ b/lib/cache/IdleFileCachePlugin.js
@@ -199,11 +199,18 @@ class IdleFileCachePlugin {
}s.`
);
}
- idleTimer = setTimeout(() => {
- idleTimer = undefined;
- isIdle = true;
- resolvedPromise.then(processIdleTasks);
- }, Math.min(isInitialStore ? idleTimeoutForInitialStore : Infinity, isLargeChange ? idleTimeoutAfterLargeChanges : Infinity, idleTimeout));
+ idleTimer = setTimeout(
+ () => {
+ idleTimer = undefined;
+ isIdle = true;
+ resolvedPromise.then(processIdleTasks);
+ },
+ Math.min(
+ isInitialStore ? idleTimeoutForInitialStore : Infinity,
+ isLargeChange ? idleTimeoutAfterLargeChanges : Infinity,
+ idleTimeout
+ )
+ );
idleTimer.unref();
}
);
diff --git a/lib/cache/PackFileCacheStrategy.js b/lib/cache/PackFileCacheStrategy.js
index 3462e914c40..be0a6a56cb9 100644
--- a/lib/cache/PackFileCacheStrategy.js
+++ b/lib/cache/PackFileCacheStrategy.js
@@ -539,7 +539,7 @@ class Pack {
map.set(identifier, content.content.get(identifier));
}
return new PackContentItems(map);
- })
+ })
: undefined;
}
}
@@ -1046,8 +1046,8 @@ class PackFileCacheStrategy {
compression === "brotli"
? ".pack.br"
: compression === "gzip"
- ? ".pack.gz"
- : ".pack";
+ ? ".pack.gz"
+ : ".pack";
this.snapshot = snapshot;
/** @type {Set} */
this.buildDependencies = new Set();
diff --git a/lib/cache/ResolverCachePlugin.js b/lib/cache/ResolverCachePlugin.js
index 4659d617a3c..b402731d26c 100644
--- a/lib/cache/ResolverCachePlugin.js
+++ b/lib/cache/ResolverCachePlugin.js
@@ -264,7 +264,7 @@ class ResolverCachePlugin {
yields = undefined;
callbacks = false;
}
- }
+ }
: (err, result) => {
if (callbacks === undefined) {
callback(err, result);
@@ -276,7 +276,7 @@ class ResolverCachePlugin {
activeRequests.delete(identifier);
callbacks = false;
}
- };
+ };
/**
* @param {Error=} err error if any
* @param {CacheEntry=} cacheEntry cache entry
diff --git a/lib/config/browserslistTargetHandler.js b/lib/config/browserslistTargetHandler.js
index 6a0e8a739cb..eba8459e05c 100644
--- a/lib/config/browserslistTargetHandler.js
+++ b/lib/config/browserslistTargetHandler.js
@@ -60,11 +60,11 @@ const load = (input, context) => {
const config = query
? query
: configPath
- ? browserslist.loadConfig({
- config: configPath,
- env
- })
- : browserslist.loadConfig({ path: context, env });
+ ? browserslist.loadConfig({
+ config: configPath,
+ env
+ })
+ : browserslist.loadConfig({ path: context, env });
if (!config) return;
return browserslist(config);
@@ -90,7 +90,9 @@ const resolve = browsers => {
// safari TP supports all features for normal safari
parsedVersion === "TP"
? [Infinity, Infinity]
- : parsedVersion.split(".");
+ : parsedVersion.includes("-")
+ ? parsedVersion.split("-")[0].split(".")
+ : parsedVersion.split(".");
if (typeof requiredVersion === "number") {
return +parsedMajor >= requiredVersion;
}
@@ -118,8 +120,8 @@ const resolve = browsers => {
samsung: [8, 2],
android: 63,
and_qq: [10, 4],
- // baidu: Not supported
- // and_uc: Not supported
+ baidu: [13, 18],
+ and_uc: [15, 5],
kaios: [3, 0],
node: [12, 17]
});
@@ -144,7 +146,7 @@ const resolve = browsers => {
android: 37,
and_qq: [10, 4],
// Supported correctly in strict mode, otherwise supported without block scope
- // baidu: Not supported
+ baidu: [13, 18],
and_uc: [12, 12],
kaios: [2, 5],
node: [6, 0]
@@ -222,9 +224,9 @@ const resolve = browsers => {
ios_saf: 14,
samsung: [9, 2],
android: 67,
- // and_qq: Not supported
- // baidu: Not supported
- // and_uc: Not supported
+ and_qq: [13, 1],
+ baidu: [13, 18],
+ and_uc: [15, 5],
kaios: [3, 0],
node: [10, 4]
}),
@@ -244,8 +246,8 @@ const resolve = browsers => {
samsung: [8, 0],
android: 61,
and_qq: [10, 4],
- // baidu: Not supported
- // and_uc: Not supported
+ baidu: [13, 18],
+ and_uc: [15, 5],
kaios: [3, 0],
node: [12, 17]
}),
@@ -310,6 +312,25 @@ const resolve = browsers => {
kaios: [2, 5],
node: 4
}),
+ asyncFunction: rawChecker({
+ chrome: 55,
+ and_chr: 55,
+ edge: 15,
+ firefox: 52,
+ and_ff: 52,
+ // ie: Not supported,
+ opera: 42,
+ op_mob: 42,
+ safari: 11,
+ ios_saf: 11,
+ samsung: [6, 2],
+ android: 55,
+ and_qq: [13, 1],
+ baidu: [13, 18],
+ and_uc: [15, 5],
+ kaios: 3,
+ node: [7, 6]
+ }),
browser: browserProperty,
electron: false,
node: nodeProperty,
diff --git a/lib/config/defaults.js b/lib/config/defaults.js
index 097e62ea0e0..2b8292e526c 100644
--- a/lib/config/defaults.js
+++ b/lib/config/defaults.js
@@ -29,7 +29,8 @@ const {
/** @typedef {import("../../declarations/WebpackOptions").CacheOptionsNormalized} CacheOptions */
/** @typedef {import("../../declarations/WebpackOptions").Context} Context */
-/** @typedef {import("../../declarations/WebpackOptions").CssExperimentOptions} CssExperimentOptions */
+/** @typedef {import("../../declarations/WebpackOptions").CssGeneratorOptions} CssGeneratorOptions */
+/** @typedef {import("../../declarations/WebpackOptions").CssParserOptions} CssParserOptions */
/** @typedef {import("../../declarations/WebpackOptions").EntryDescription} EntryDescription */
/** @typedef {import("../../declarations/WebpackOptions").EntryNormalized} Entry */
/** @typedef {import("../../declarations/WebpackOptions").EntryStaticNormalized} EntryStaticNormalized */
@@ -39,6 +40,7 @@ const {
/** @typedef {import("../../declarations/WebpackOptions").ExternalsPresets} ExternalsPresets */
/** @typedef {import("../../declarations/WebpackOptions").ExternalsType} ExternalsType */
/** @typedef {import("../../declarations/WebpackOptions").FileCacheOptions} FileCacheOptions */
+/** @typedef {import("../../declarations/WebpackOptions").GeneratorOptionsByModuleTypeKnown} GeneratorOptionsByModuleTypeKnown */
/** @typedef {import("../../declarations/WebpackOptions").InfrastructureLogging} InfrastructureLogging */
/** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */
/** @typedef {import("../../declarations/WebpackOptions").Library} Library */
@@ -159,11 +161,11 @@ const applyWebpackOptionsDefaults = options => {
target === false
? /** @type {false} */ (false)
: typeof target === "string"
- ? getTargetProperties(target, /** @type {Context} */ (options.context))
- : getTargetsProperties(
- /** @type {string[]} */ (target),
- /** @type {Context} */ (options.context)
- );
+ ? getTargetProperties(target, /** @type {Context} */ (options.context))
+ : getTargetsProperties(
+ /** @type {string[]} */ (target),
+ /** @type {Context} */ (options.context)
+ );
const development = mode === "development";
const production = mode === "production" || !mode;
@@ -223,7 +225,8 @@ const applyWebpackOptionsDefaults = options => {
/** @type {NonNullable} */
(options.experiments.css),
futureDefaults,
- isNode: targetProperties && targetProperties.node === true
+ isNode: targetProperties && targetProperties.node === true,
+ targetProperties
});
applyOutputDefaults(options.output, {
@@ -260,14 +263,15 @@ const applyWebpackOptionsDefaults = options => {
validExternalTypes.includes(options.output.library.type)
? /** @type {ExternalsType} */ (options.output.library.type)
: options.output.module
- ? "module"
- : "var";
+ ? "module"
+ : "var";
});
applyNodeDefaults(options.node, {
futureDefaults:
/** @type {NonNullable} */
(options.experiments.futureDefaults),
+ outputModule: options.output.module,
targetProperties
});
@@ -335,7 +339,7 @@ const applyExperimentsDefaults = (
D(experiments, "lazyCompilation", undefined);
D(experiments, "buildHttp", undefined);
D(experiments, "cacheUnaffected", experiments.futureDefaults);
- F(experiments, "css", () => (experiments.futureDefaults ? {} : undefined));
+ F(experiments, "css", () => (experiments.futureDefaults ? true : undefined));
// TODO webpack 6: remove this. topLevelAwait should be enabled by default
let shouldEnableTopLevelAwait = true;
@@ -348,14 +352,6 @@ const applyExperimentsDefaults = (
D(experiments.buildHttp, "frozen", production);
D(experiments.buildHttp, "upgrade", false);
}
-
- if (typeof experiments.css === "object") {
- D(
- experiments.css,
- "exportsOnly",
- !targetProperties || !targetProperties.document
- );
- }
};
/**
@@ -448,7 +444,7 @@ const applySnapshotDefaults = (snapshot, { production, futureDefaults }) => {
process.versions.pnp === "3"
? [
/^(.+?(?:[\\/]\.yarn[\\/]unplugged[\\/][^\\/]+)?[\\/]node_modules[\\/])/
- ]
+ ]
: [/^(.+?[\\/]node_modules[\\/])/]
);
F(snapshot, "immutablePaths", () =>
@@ -468,7 +464,6 @@ const applySnapshotDefaults = (snapshot, { production, futureDefaults }) => {
}
} else {
const match = /^(.+?[\\/]node_modules[\\/])/.exec(
- // eslint-disable-next-line node/no-extraneous-require
require.resolve("watchpack")
);
if (match) {
@@ -477,6 +472,7 @@ const applySnapshotDefaults = (snapshot, { production, futureDefaults }) => {
}
return [];
});
+ F(snapshot, "unmanagedPaths", () => []);
A(snapshot, "immutablePaths", () => {
if (process.versions.pnp === "1") {
const match =
@@ -543,20 +539,46 @@ const applyJavascriptParserOptionsDefaults = (
if (futureDefaults) D(parserOptions, "exportsPresence", "error");
};
+/**
+ * @param {CssGeneratorOptions} generatorOptions generator options
+ * @param {Object} options options
+ * @param {TargetProperties | false} options.targetProperties target properties
+ * @returns {void}
+ */
+const applyCssGeneratorOptionsDefaults = (
+ generatorOptions,
+ { targetProperties }
+) => {
+ D(
+ generatorOptions,
+ "exportsOnly",
+ !targetProperties || !targetProperties.document
+ );
+};
+
/**
* @param {ModuleOptions} module options
* @param {Object} options options
* @param {boolean} options.cache is caching enabled
* @param {boolean} options.syncWebAssembly is syncWebAssembly enabled
* @param {boolean} options.asyncWebAssembly is asyncWebAssembly enabled
- * @param {CssExperimentOptions|false} options.css is css enabled
+ * @param {boolean} options.css is css enabled
* @param {boolean} options.futureDefaults is future defaults enabled
* @param {boolean} options.isNode is node target platform
+ * @param {TargetProperties | false} options.targetProperties target properties
* @returns {void}
*/
const applyModuleDefaults = (
module,
- { cache, syncWebAssembly, asyncWebAssembly, css, futureDefaults, isNode }
+ {
+ cache,
+ syncWebAssembly,
+ asyncWebAssembly,
+ css,
+ futureDefaults,
+ isNode,
+ targetProperties
+ }
) => {
if (cache) {
D(
@@ -607,6 +629,20 @@ const applyModuleDefaults = (
}
);
+ if (css) {
+ F(module.parser, "css", () => ({}));
+
+ D(module.parser.css, "namedExports", true);
+
+ F(module.generator, "css", () => ({}));
+
+ applyCssGeneratorOptionsDefaults(
+ /** @type {NonNullable} */
+ (module.generator.css),
+ { targetProperties }
+ );
+ }
+
A(module, "defaultRules", () => {
const esm = {
type: JAVASCRIPT_MODULE_TYPE_ESM,
@@ -818,9 +854,8 @@ const applyOutputDefaults = (
} catch (e) {
if (/** @type {Error & { code: string }} */ (e).code !== "ENOENT") {
/** @type {Error & { code: string }} */
- (
- e
- ).message += `\nwhile determining default 'output.uniqueName' from 'name' in ${pkgPath}`;
+ (e).message +=
+ `\nwhile determining default 'output.uniqueName' from 'name' in ${pkgPath}`;
throw e;
}
return "";
@@ -870,22 +905,11 @@ const applyOutputDefaults = (
D(output, "webassemblyModuleFilename", "[hash].module.wasm");
D(output, "compareBeforeEmit", true);
D(output, "charset", true);
- F(output, "hotUpdateGlobal", () =>
- Template.toIdentifier(
- "webpackHotUpdate" +
- Template.toIdentifier(
- /** @type {NonNullable