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..1a22fcd8a8a 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"
@@ -52,9 +52,9 @@ jobs:
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,16 +64,16 @@ 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 }}
@@ -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,7 +134,7 @@ 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 }}
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/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-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-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/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/lib/APIPlugin.js b/lib/APIPlugin.js
index cd4dd872199..94b617df620 100644
--- a/lib/APIPlugin.js
+++ b/lib/APIPlugin.js
@@ -247,7 +247,7 @@ class APIPlugin {
? new BasicEvaluatedExpression().setNull()
: new BasicEvaluatedExpression().setString(
parser.state.module.layer
- )
+ )
).setRange(expr.range)
);
parser.hooks.evaluateTypeof
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..c17748d5cc8 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"),
@@ -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/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/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..6cbd7035b79 100644
--- a/lib/EvalSourceMapDevToolPlugin.js
+++ b/lib/EvalSourceMapDevToolPlugin.js
@@ -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/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..16becbfbf42 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) => void} 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__"),
+ expr.range,
+ expressionName
+ );
+ dep.loc = 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/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/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..77f0d4aab73 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);
@@ -310,6 +310,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: [10, 1],
+ ios_saf: [10, 3],
+ samsung: 6,
+ android: 55,
+ // and_qq: Unknown support
+ // baidu: Unknown support
+ // and_uc: Unknown support
+ // kaios: Unknown support
+ node: [7, 6]
+ }),
browser: browserProperty,
electron: false,
node: nodeProperty,
diff --git a/lib/config/defaults.js b/lib/config/defaults.js
index 097e62ea0e0..6ad22ad0a11 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) {
@@ -543,20 +538,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 +628,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 +853,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 +904,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