From 84ebcc2ef1b3eed12adfa0b53c1ac6b0db0a4d9f Mon Sep 17 00:00:00 2001 From: Deeksha Varshney Date: Thu, 20 Nov 2025 10:27:45 +0530 Subject: [PATCH 1/8] docs: Update Getting Started guide to ES Modules syntax --- src/content/guides/getting-started.mdx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/content/guides/getting-started.mdx b/src/content/guides/getting-started.mdx index 79ef48512356..c09b48c96809 100644 --- a/src/content/guides/getting-started.mdx +++ b/src/content/guides/getting-started.mdx @@ -250,9 +250,9 @@ As of version 4, webpack doesn't require any configuration, but most projects wi **webpack.config.js** ```javascript -const path = require('path'); +import path from 'path'; -module.exports = { +export default { entry: './src/index.js', output: { filename: 'main.js', From 81bb7aa747e518f0283e28414c8e590d16391cd9 Mon Sep 17 00:00:00 2001 From: Deeksha Varshney Date: Thu, 20 Nov 2025 11:14:01 +0530 Subject: [PATCH 2/8] docs: Update Asset Management guide to ES Modules syntax (fixes #7636) --- package.json | 1 + 1 file changed, 1 insertion(+) diff --git a/package.json b/package.json index 8a191d76f306..4e926b5d4fcd 100644 --- a/package.json +++ b/package.json @@ -152,6 +152,7 @@ "dependencies": { "@docsearch/react": "^3.9.0", "@react-spring/web": "^9.7.5", + "ajv-keywords": "^3.5.2", "path-browserify": "^1.0.1", "prop-types": "^15.8.1", "react": "^17.0.2", From a78a4dbe9d2563328874b3aeace43eae6454f4a6 Mon Sep 17 00:00:00 2001 From: Deeksha Varshney Date: Sat, 6 Dec 2025 18:49:26 +0530 Subject: [PATCH 3/8] successfully update --- package.json | 1 - 1 file changed, 1 deletion(-) diff --git a/package.json b/package.json index 4e926b5d4fcd..8a191d76f306 100644 --- a/package.json +++ b/package.json @@ -152,7 +152,6 @@ "dependencies": { "@docsearch/react": "^3.9.0", "@react-spring/web": "^9.7.5", - "ajv-keywords": "^3.5.2", "path-browserify": "^1.0.1", "prop-types": "^15.8.1", "react": "^17.0.2", From 53cba256b7f34a71535f407274baf86361b6d15b Mon Sep 17 00:00:00 2001 From: Deeksha Varshney Date: Sat, 13 Dec 2025 23:27:45 +0530 Subject: [PATCH 4/8] docs: Migrate configuration and plugin examples to ES Modules syntax --- src/components/Footer/Footer.jsx | 5 +- src/content/api/cli.mdx | 6 +- src/content/api/loaders.mdx | 74 +++--- src/content/api/logging.mdx | 8 +- src/content/api/module-variables.mdx | 18 +- .../blog/2020-10-10-webpack-5-release.mdx | 22 +- src/content/comparison.mdx | 10 +- src/content/concepts/configuration.mdx | 10 +- src/content/concepts/entry-points.mdx | 24 +- src/content/concepts/index.mdx | 22 +- src/content/concepts/loaders.mdx | 4 +- src/content/concepts/module-federation.mdx | 10 +- src/content/concepts/output.mdx | 10 +- src/content/concepts/plugins.mdx | 16 +- src/content/concepts/targets.mdx | 6 +- src/content/concepts/under-the-hood.mdx | 6 +- src/content/configuration/cache.mdx | 46 ++-- .../configuration/configuration-languages.mdx | 12 +- .../configuration/configuration-types.mdx | 14 +- src/content/configuration/dev-server.mdx | 180 +++++++------- src/content/configuration/entry-context.mdx | 24 +- src/content/configuration/experiments.mdx | 20 +- .../extending-configurations.mdx | 28 ++- src/content/configuration/externals.mdx | 100 ++++---- .../configuration/infrastructureLogging.mdx | 12 +- src/content/configuration/mode.mdx | 10 +- src/content/configuration/module.mdx | 138 +++++------ src/content/configuration/node.mdx | 2 +- src/content/configuration/optimization.mdx | 64 +++-- src/content/configuration/other-options.mdx | 33 ++- src/content/configuration/output.mdx | 228 +++++++++--------- src/content/configuration/performance.mdx | 12 +- src/content/configuration/plugins.mdx | 8 +- src/content/configuration/resolve.mdx | 132 +++++----- src/content/configuration/stats.mdx | 162 ++++++------- src/content/configuration/target.mdx | 12 +- src/content/configuration/watch.mdx | 26 +- src/content/contribute/plugin-patterns.mdx | 14 +- src/content/contribute/writing-a-loader.mdx | 25 +- src/content/contribute/writing-a-plugin.mdx | 25 +- src/content/guides/asset-management.mdx | 40 +-- src/content/guides/asset-modules.mdx | 46 ++-- src/content/guides/author-libraries.mdx | 38 ++- src/content/guides/build-performance.mdx | 17 +- src/content/guides/caching.mdx | 36 ++- src/content/guides/code-splitting.mdx | 35 ++- src/content/guides/development-vagrant.mdx | 7 +- src/content/guides/development.mdx | 45 ++-- src/content/guides/entry-advanced.mdx | 4 +- src/content/guides/environment-variables.mdx | 7 +- src/content/guides/hot-module-replacement.mdx | 38 +-- src/content/guides/integrations.mdx | 15 +- src/content/guides/output-management.mdx | 25 +- src/content/guides/package-exports.mdx | 4 +- src/content/guides/production.mdx | 25 +- .../guides/progressive-web-application.mdx | 11 +- src/content/guides/public-path.mdx | 2 +- src/content/guides/shimming.mdx | 43 ++-- src/content/guides/tree-shaking.mdx | 15 +- src/content/guides/typescript.mdx | 14 +- src/content/migrate/3.mdx | 32 ++- src/content/migrate/4.mdx | 14 +- src/content/migrate/5.mdx | 40 ++- src/content/plugins/NoEmitOnErrorsPlugin.mdx | 4 +- .../plugins/automatic-prefetch-plugin.mdx | 9 +- src/content/plugins/commons-chunk-plugin.mdx | 18 +- .../plugins/context-exclusion-plugin.mdx | 8 +- src/content/plugins/define-plugin.mdx | 1 - src/content/plugins/dll-plugin.mdx | 18 +- .../eval-source-map-dev-tool-plugin.mdx | 7 +- src/content/plugins/html-webpack-plugin.mdx | 9 +- .../plugins/limit-chunk-count-plugin.mdx | 6 +- .../plugins/module-concatenation-plugin.mdx | 4 +- .../plugins/module-federation-plugin.mdx | 60 +++-- .../normal-module-replacement-plugin.mdx | 12 +- src/content/plugins/provide-plugin.mdx | 18 +- .../plugins/source-map-dev-tool-plugin.mdx | 12 +- src/content/plugins/split-chunks-plugin.mdx | 44 ++-- src/content/plugins/virtual-url-plugin.mdx | 14 +- src/styles/partials/_vars.scss | 19 +- 80 files changed, 1320 insertions(+), 1074 deletions(-) diff --git a/src/components/Footer/Footer.jsx b/src/components/Footer/Footer.jsx index eed125728c64..317fdfec5c05 100644 --- a/src/components/Footer/Footer.jsx +++ b/src/components/Footer/Footer.jsx @@ -39,7 +39,10 @@ const Footer = () => ( Branding - + Discord { +export default (env, argv) => { return { mode: env.WEBPACK_SERVE ? 'development' : 'production', }; @@ -649,7 +649,7 @@ When the `mode` option is not specified in the configuration, you can use the `- If your configuration exports a function, the value of `--config-node-env` is assigned to mode after the function returns. This means that `mode` will not be available in the function arguments (`env` and `argv`). However, the value of `--config-node-env` is accessible as `argv.nodeEnv` within the function and can be used accordingly. ```javascript -module.exports = (env, argv) => { +export default (env, argv) => { console.log(argv.defineProcessEnvNodeEnv); // 'production' if --config-node-env production is used return { // your configuration diff --git a/src/content/api/loaders.mdx b/src/content/api/loaders.mdx index 4c9a2620a260..73977b67691d 100644 --- a/src/content/api/loaders.mdx +++ b/src/content/api/loaders.mdx @@ -48,9 +48,9 @@ Either `return` or `this.callback` can be used to return the transformed `conten **sync-loader.js** ```javascript -module.exports = function (content, map, meta) { +export default function (content, map, meta) { return someSyncOperation(content); -}; +} ``` The `this.callback` method is more flexible as you pass multiple arguments instead of using `content` only. @@ -58,10 +58,10 @@ The `this.callback` method is more flexible as you pass multiple arguments inste **sync-loader-with-multiple-results.js** ```javascript -module.exports = function (content, map, meta) { +export default function (content, map, meta) { this.callback(null, someSyncOperation(content), map, meta); return; // always return undefined when calling callback() -}; +} ``` ### Asynchronous Loaders @@ -71,10 +71,10 @@ For asynchronous loaders, you can return the transformed `content` from an `asyn **async-loader.js** ```javascript -module.exports = async function (content, map, meta) { +export default async function (content, map, meta) { var result = await someAsyncOperation(content); return result; -}; +} ``` Or you can use [`this.async`](#thisasync) to retrieve the `callback` function: @@ -82,25 +82,25 @@ Or you can use [`this.async`](#thisasync) to retrieve the `callback` function: **async-loader-with-callback.js** ```javascript -module.exports = function (content, map, meta) { +export default function (content, map, meta) { var callback = this.async(); someAsyncOperation(content, function (err, result) { if (err) return callback(err); callback(null, result, map, meta); }); -}; +} ``` **async-loader-with-multiple-results.js** ```javascript -module.exports = function (content, map, meta) { +export default function (content, map, meta) { var callback = this.async(); someAsyncOperation(content, function (err, result, sourceMaps, meta) { if (err) return callback(err); callback(null, result, sourceMaps, meta); }); -}; +} ``` T> Loaders were originally designed to work in synchronous loader pipelines, like Node.js (using [enhanced-require](https://github.com/webpack/enhanced-require)), _and_ asynchronous pipelines, like in webpack. However, since expensive synchronous computations are a bad idea in a single-threaded environment like Node.js, we advise making your loader asynchronous if possible. Synchronous loaders are ok if the amount of computation is trivial. @@ -112,13 +112,13 @@ By default, the resource file is converted to a UTF-8 string and passed to the l **raw-loader.js** ```javascript -module.exports = function (content) { +export default function (content) { assert(content instanceof Buffer); return someSyncOperation(content); // return value can be a `Buffer` too // This is also allowed if loader is not "raw" -}; -module.exports.raw = true; +} +export const raw = true; ``` ### Pitching Loader @@ -130,7 +130,7 @@ T> Loaders may be added inline in requests and disabled via inline prefixes, whi For the following configuration of [`use`](/configuration/module/#ruleuse): ```javascript -module.exports = { +export default { //... module: { rules: [ @@ -160,11 +160,11 @@ So why might a loader take advantage of the "pitching" phase? First, the `data` passed to the `pitch` method is exposed in the execution phase as well under `this.data` and could be useful for capturing and sharing information from earlier in the cycle. ```javascript -module.exports = function (content) { +export default function (content) { return someSyncOperation(content, this.data.value); -}; +} -module.exports.pitch = function (remainingRequest, precedingRequest, data) { +export const pitch = function (remainingRequest, precedingRequest, data) { data.value = 42; }; ``` @@ -172,14 +172,14 @@ module.exports.pitch = function (remainingRequest, precedingRequest, data) { Second, if a loader delivers a result in the `pitch` method, the process turns around and skips the remaining loaders. In our example above, if the `b-loader`s `pitch` method returned something: ```javascript -module.exports = function (content) { +export default function (content) { return someSyncOperation(content); -}; +} -module.exports.pitch = function (remainingRequest, precedingRequest, data) { +export const pitch = function (remainingRequest, precedingRequest, data) { if (someCondition()) { return ( - 'module.exports = require(' + + 'export default import.meta.require(' + JSON.stringify('-!' + remainingRequest) + ');' ); @@ -397,10 +397,10 @@ All dependencies of the resolving operation are automatically added as dependenc Information about HMR for loaders. ```javascript -module.exports = function (source) { +export default function (source) { console.log(this.hot); // true if HMR is enabled via --hot flag or webpack configuration return source; -}; +} ``` ### this.hashDigest @@ -452,7 +452,7 @@ An alternative lightweight solution for the child compiler to compile and execut **webpack.config.js** ```js -module.exports = { +export default { module: { rules: [ { @@ -624,7 +624,7 @@ Access to the following utilities. **my-sync-loader.js** ```js -module.exports = function (content) { +export default function (content) { this.utils.contextify( this.context, this.utils.absolutify(this.context, './index.js') @@ -637,7 +637,7 @@ module.exports = function (content) { mainHash.digest('hex'); // … return content; -}; +} ``` ### this.version @@ -711,9 +711,9 @@ Throwing an error from loader: **./src/loader.js** ```javascript -module.exports = function (source) { +export default function (source) { throw new Error('This is a Fatal Error!'); -}; +} ``` Or pass an error to the callback in async mode: @@ -721,11 +721,11 @@ Or pass an error to the callback in async mode: **./src/loader.js** ```javascript -module.exports = function (source) { +export default function (source) { const callback = this.async(); //... callback(new Error('This is a Fatal Error!'), source); -}; +} ``` The module will get bundled like this: @@ -738,7 +738,7 @@ The module will get bundled like this: /*! no static exports found */ /***/ (function(module, exports) { -throw new Error("Module build failed (from ./src/loader.js):\nError: This is a Fatal Error!\n at Object.module.exports (/workspace/src/loader.js:3:9)"); +throw new Error("Module build failed (from ./src/loader.js):\nError: This is a Fatal Error!\n at Object. (/workspace/src/loader.js:3:9)"); /***/ }) ``` @@ -749,7 +749,7 @@ Then the build output will also display the error (Similar to `this.emitError`): ERROR in ./src/lib.js (./src/loader.js!./src/lib.js) Module build failed (from ./src/loader.js): Error: This is a Fatal Error! - at Object.module.exports (/workspace/src/loader.js:2:9) + at Object. (/workspace/src/loader.js:2:9) @ ./src/index.js 1:0-25 ``` @@ -801,9 +801,9 @@ The loader could look like this: **extract-style-loader/index.js** ```javascript -const getStylesLoader = require.resolve('./getStyles'); +import getStylesLoader from './getStyles'; -module.exports = function (source) { +export default function (source) { if (STYLES_REGEXP.test(source)) { source = source.replace(STYLES_REGEXP, ''); return `import ${JSON.stringify( @@ -814,16 +814,16 @@ module.exports = function (source) { )};${source}`; } return source; -}; +} ``` **extract-style-loader/getStyles.js** ```javascript -module.exports = function (source) { +export default function (source) { const match = source.match(STYLES_REGEXP); return match[0]; -}; +} ``` ## Logging diff --git a/src/content/api/logging.mdx b/src/content/api/logging.mdx index 34e5df7f1bd9..a3b50f12e122 100644 --- a/src/content/api/logging.mdx +++ b/src/content/api/logging.mdx @@ -50,12 +50,12 @@ export class MyWebpackPlugin { **my-webpack-loader.js** ```js -module.exports = function (source) { +export default function (source) { // you can get Logger with `this.getLogger` in your webpack loaders const logger = this.getLogger('my-webpack-loader'); logger.info('hello Logger'); return source; -}; +} ``` As you can see from the above `my-webpack-plugin.js` example, there're two types of logging methods, @@ -84,12 +84,12 @@ It's advised to use `compilation.getLogger` when plugin/logging is related to th Runtime logger API is only intended to be used as a development tool, it is not intended to be included in [production mode](/configuration/mode/#mode-production). -- `const logging = require('webpack/lib/logging/runtime')`: to use the logger in runtime, require it directly from webpack +- `import logging from 'webpack/lib/logging/runtime';`: to use the logger in runtime, import it directly from webpack - `logging.getLogger('name')`: to get individual logger by name - `logging.configureDefaultLogger(...)`: to override the default logger. ```javascript -const logging = require('webpack/lib/logging/runtime'); +import logging from 'webpack/lib/logging/runtime'; logging.configureDefaultLogger({ level: 'log', debug: /something/, diff --git a/src/content/api/module-variables.mdx b/src/content/api/module-variables.mdx index 7b24630569ee..5782d8c8d085 100644 --- a/src/content/api/module-variables.mdx +++ b/src/content/api/module-variables.mdx @@ -36,7 +36,7 @@ Indicates whether or not [Hot Module Replacement](/concepts/hot-module-replaceme The ID of the current module. ```javascript -module.id === require.resolve('./file.js'); +console.log('Current module ID concept is available via import.meta'); ``` ## module.exports (CommonJS) @@ -44,9 +44,9 @@ module.id === require.resolve('./file.js'); Defines the value that will be returned when a consumer makes a `require` call to the module (defaults to a new object). ```javascript -module.exports = function doSomething() { +export default function doSomething() { // Do something... -}; +} ``` W> This CANNOT be used in an asynchronous function. @@ -56,13 +56,13 @@ W> This CANNOT be used in an asynchronous function. This variable is equal to the default value of `module.exports` (i.e. an object). If `module.exports` gets overwritten, `exports` will no longer be exported. ```javascript -exports.someValue = 42; -exports.anObject = { +export const someValue = 42; +export const anObject = { x: 123, }; -exports.aFunction = function doSomething() { +export function aFunction() { // Do something -}; +} ``` ## global (NodeJS) @@ -170,7 +170,7 @@ If used inside an expression that is parsed by the Parser, the configuration opt The resource query of the current module. If the following `require` call was made, then the query string would be available in `file.js`. ```javascript -require('file.js?test'); +import 'file.js?test'; ``` **file.js** @@ -265,14 +265,12 @@ In modules, `__webpack_exports_info__` is available to allow exports introspecti - `__webpack_exports_info__..used` is `false` when the export is known to be unused, `true` otherwise - `__webpack_exports_info__..useInfo` is - - `false` when the export is known to be unused - `true` when the export is known to be used - `null` when the export usage could depend on runtime conditions - `undefined` when no info is available - `__webpack_exports_info__..provideInfo` is - - `false` when the export is known to be not provided - `true` when the export is known to be provided - `null` when the export provision could depend on runtime conditions diff --git a/src/content/blog/2020-10-10-webpack-5-release.mdx b/src/content/blog/2020-10-10-webpack-5-release.mdx index 065cb96504f5..87a374b04fff 100644 --- a/src/content/blog/2020-10-10-webpack-5-release.mdx +++ b/src/content/blog/2020-10-10-webpack-5-release.mdx @@ -390,7 +390,7 @@ Webpack 5 adds support for some CommonJs constructs, allows to eliminate unused The following constructs are supported: - `exports|this|module.exports.xxx = ...` -- `exports|this|module.exports = require("...")` (reexport) +- `exports|this|export default require("...")` (reexport) - `exports|this|module.exports.xxx = require("...").xxx` (reexport) - `Object.defineProperty(exports|this|module.exports, "xxx", ...)` - `require("abc").xxx` @@ -496,7 +496,7 @@ The SplitChunksPlugin now knows how to handle these different sizes and uses the By default, only `javascript` size is handled, but you can now pass multiple values to manage them: ```js -module.exports = { +export default { optimization: { splitChunks: { minSize: { @@ -519,7 +519,7 @@ The `mini-css-extract-plugin` uses `css/mini-extra` as size type, and adds this There is now a filesystem cache. It's opt-in and can be enabled with the following configuration: ```js -module.exports = { +export default { cache: { // 1. Set cache type to filesystem type: 'filesystem', @@ -880,7 +880,7 @@ There is a compat-layer, so Main/Chunk/ModuleTemplate still exist, but only dele If an object is passed as entry point the value might be a string, array of strings or a descriptor: ```js -module.exports = { +export default { entry: { catalog: { import: './catalog.js', @@ -896,7 +896,7 @@ Descriptor syntax might be used to pass additional options to an entry point. By default, the output filename for the entry chunk is extracted from `output.filename` but you can specify a custom output filename for a specific entry: ```js -module.exports = { +export default { entry: { about: { import: './about.js', filename: 'pages/[name][ext]' }, }, @@ -908,7 +908,7 @@ module.exports = { By default, every entry chunk stores all the modules that it uses. With `dependOn`-option you can share the modules from one entry chunk to another: ```js -module.exports = { +export default { entry: { app: { import: './app.js', dependOn: 'react-vendors' }, 'react-vendors': ['react', 'react-dom', 'prop-types'], @@ -923,7 +923,7 @@ The app chunk will not contain the modules that `react-vendors` has. The entry descriptor allows to pass a different `library` option for each entrypoint. ```js -module.exports = { +export default { entry: { commonjs: { import: './lib.js', @@ -949,7 +949,7 @@ When multiple entries specify the same `runtime`, that chunk will contain a comm This means they could be used together on the same HTML page. ```js -module.exports = { +export default { entry: { app: { import: './app.js', @@ -965,7 +965,7 @@ The entry descriptor allows to specify a `chunkLoading` per entry. The runtime for this entry will use this to load chunks. ```js -module.exports = { +export default { entry: { app: { import: './app.js', @@ -1160,7 +1160,7 @@ These dependencies are cheaper to process and webpack uses them when possible It will be deprecated. Use ```js - module.exports = { + export default { resolve: { alias: { xyz$: false, @@ -1172,7 +1172,7 @@ These dependencies are cheaper to process and webpack uses them when possible or use an absolute path ```js - module.exports = { + export default { resolve: { alias: { [path.resolve(__dirname, '....')]: false, diff --git a/src/content/comparison.mdx b/src/content/comparison.mdx index 61150db89d8c..8658254f9f94 100644 --- a/src/content/comparison.mdx +++ b/src/content/comparison.mdx @@ -26,14 +26,14 @@ Webpack is not the only module bundler out there. If you are choosing between us | CommonJS `exports` | **yes** | only wrapping in `define` | **yes** | yes | [commonjs-plugin](https://github.com/rollup/rollup-plugin-commonjs) | yes | | CommonJS `require` | **yes** | only wrapping in `define` | **yes** | yes | [commonjs-plugin](https://github.com/rollup/rollup-plugin-commonjs) | yes | | CommonJS `require.resolve` | **yes** | no | no | no | no | | -| Concat in require `require("./fi" + "le")` | **yes** | no♦ | no | no | no | | +| Concat in require `require("./fi" + "le")` | **yes** | no♦ | no | no | no | | | Debugging support | **SourceUrl, SourceMaps** | not required | SourceMaps | **SourceUrl, SourceMaps** | **SourceUrl, SourceMaps** | SourceMaps | | Dependencies | 19MB / 127 packages | 11MB / 118 packages | **1.2MB / 1 package** | 26MB / 131 packages | ?MB / 3 packages | | | ES2015 `import`/`export` | **yes** (webpack 2) | no | no | **yes** | **yes** | yes, via [es6 module transpiler](https://github.com/gcollazo/es6-module-transpiler-brunch) | -| Expressions in require (guided) `require("./templates/" + template)` | **yes (all files matching included)** | no♦ | no | no | no | no | -| Expressions in require (free) `require(moduleName)` | with manual configuration | no♦ | no | no | no | | -| Generate a single bundle | **yes** | yes♦ | yes | yes | yes | yes | -| Indirect require `var r = require; r("./file")` | **yes** | no♦ | no | no | no | | +| Expressions in require (guided) `require("./templates/" + template)` | **yes (all files matching included)** | no♦ | no | no | no | no | +| Expressions in require (free) `require(moduleName)` | with manual configuration | no♦ | no | no | no | | +| Generate a single bundle | **yes** | yes♦ | yes | yes | yes | yes | +| Indirect require `var r = require; r("./file")` | **yes** | no♦ | no | no | no | | | Load each file separate | no | yes | no | yes | no | no | | Mangle path names | **yes** | no | partial | yes | not required (path names are not included in the bundle) | no | | Minimizing | [Terser](https://github.com/fabiosantoscode/terser) | uglify, closure compiler | [uglifyify](https://github.com/hughsk/uglifyify) | yes | [uglify-plugin](https://github.com/TrySound/rollup-plugin-uglify) | [UglifyJS-brunch](https://github.com/brunch/uglify-js-brunch) | diff --git a/src/content/concepts/configuration.mdx b/src/content/concepts/configuration.mdx index e5bbce18772c..e539fe0f363a 100644 --- a/src/content/concepts/configuration.mdx +++ b/src/content/concepts/configuration.mdx @@ -10,10 +10,10 @@ contributors: You may have noticed that few webpack configurations look exactly alike. This is because **webpack's configuration file is a JavaScript file that exports a webpack [configuration](/configuration/).** This configuration is then processed by webpack based upon its defined properties. -Because it's a standard Node.js CommonJS module, you **can do the following**: +Because it's a standard Node.js module, you **can do the following**: -- Import other files via `require(...)` -- use utilities on npm via `require(...)` +- Import other files via `import(...)` +- use utilities on npm via `import(...)` - use JavaScript control flow expressions, e.g. the `?:` operator - use constants or variables for often used values - write and execute functions to generate a part of the configuration @@ -35,9 +35,9 @@ The examples below describe how webpack's configuration can be both expressive a **webpack.config.js** ```javascript -const path = require('path'); +import path from 'path'; -module.exports = { +export default { mode: 'development', entry: './foo.js', output: { diff --git a/src/content/concepts/entry-points.mdx b/src/content/concepts/entry-points.mdx index 437c8799b12d..d7dfd9796aa2 100644 --- a/src/content/concepts/entry-points.mdx +++ b/src/content/concepts/entry-points.mdx @@ -23,7 +23,7 @@ Usage: `entry: string | [string]` **webpack.config.js** ```javascript -module.exports = { +export default { entry: './path/to/my/entry/file.js', }; ``` @@ -33,7 +33,7 @@ The single entry syntax for the `entry` property is a shorthand for: **webpack.config.js** ```javascript -module.exports = { +export default { entry: { main: './path/to/my/entry/file.js', }, @@ -45,7 +45,7 @@ We can also pass an array of file paths to the `entry` property which creates wh **webpack.config.js** ```javascript -module.exports = { +export default { entry: ['./src/file_1.js', './src/file_2.js'], output: { filename: 'bundle.js', @@ -62,7 +62,7 @@ Usage: `entry: { string | [string] } | {}` **webpack.config.js** ```javascript -module.exports = { +export default { entry: { app: './src/app.js', adminApp: './src/adminApp.js', @@ -91,7 +91,7 @@ An object of entry point description. You can specify the following properties. **webpack.config.js** ```javascript -module.exports = { +export default { entry: { a2: 'dependingfile.js', b2: { @@ -107,7 +107,7 @@ module.exports = { **webpack.config.js** ```javascript -module.exports = { +export default { entry: { a2: './a', b2: { @@ -122,7 +122,7 @@ module.exports = { Make sure `runtime` must not point to an existing entry point name, for example the below config would throw an error: ```javascript -module.exports = { +export default { entry: { a1: './a', b1: { @@ -136,7 +136,7 @@ module.exports = { Also `dependOn` must not be circular, the following example again would throw an error: ```javascript -module.exports = { +export default { entry: { a3: { import: './a', @@ -159,7 +159,7 @@ Below is a list of entry configurations and their real-world use cases: **webpack.config.js** ```javascript -module.exports = { +export default { entry: { main: './src/app.js', vendor: './src/vendor.js', @@ -170,7 +170,7 @@ module.exports = { **webpack.prod.js** ```javascript -module.exports = { +export default { output: { filename: '[name].[contenthash].bundle.js', }, @@ -180,7 +180,7 @@ module.exports = { **webpack.dev.js** ```javascript -module.exports = { +export default { output: { filename: '[name].bundle.js', }, @@ -198,7 +198,7 @@ T> In webpack version < 4 it was common to add vendors as a separate entry point **webpack.config.js** ```javascript -module.exports = { +export default { entry: { pageOne: './src/pageOne/index.js', pageTwo: './src/pageTwo/index.js', diff --git a/src/content/concepts/index.mdx b/src/content/concepts/index.mdx index efa6bb6f0208..6aaded8f8e26 100644 --- a/src/content/concepts/index.mdx +++ b/src/content/concepts/index.mdx @@ -54,7 +54,7 @@ By default its value is `./src/index.js`, but you can specify a different (or mu **webpack.config.js** ```js -module.exports = { +export default { entry: './path/to/my/entry/file.js', }; ``` @@ -70,9 +70,9 @@ You can configure this part of the process by specifying an `output` field in yo **webpack.config.js** ```javascript -const path = require('path'); +import path from 'path'; -module.exports = { +export default { entry: './path/to/my/entry/file.js', output: { path: path.resolve(__dirname, 'dist'), @@ -99,9 +99,9 @@ At a high level, **loaders** have two properties in your webpack configuration: **webpack.config.js** ```javascript -const path = require('path'); +import path from 'path'; -module.exports = { +export default { output: { filename: 'my-first-webpack.bundle.js', }, @@ -113,7 +113,7 @@ module.exports = { The configuration above has defined a `rules` property for a single module with two required properties: `test` and `use`. This tells webpack's compiler the following: -> "Hey webpack compiler, when you come across a path that resolves to a '.txt' file inside of a `require()`/`import` statement, **use** the `raw-loader` to transform it before you add it to the bundle." +> "Hey webpack compiler, when you come across a path that resolves to a '.txt' file inside of a `import` statement, **use** the `raw-loader` to transform it before you add it to the bundle." W> It is important to remember that when defining rules in your webpack config, you are defining them under `module.rules` and not `rules`. For your benefit, webpack will warn you if this is done incorrectly. @@ -127,15 +127,15 @@ While loaders are used to transform certain types of modules, plugins can be lev T> Check out the [plugin interface](/api/plugins) and how to use it to extend webpack's capabilities. -In order to use a plugin, you need to `require()` it and add it to the `plugins` array. Most plugins are customizable through options. Since you can use a plugin multiple times in a configuration for different purposes, you need to create an instance of it by calling it with the `new` operator. +In order to use a plugin, you need to `import` it and add it to the `plugins` array. Most plugins are customizable through options. Since you can use a plugin multiple times in a configuration for different purposes, you need to create an instance of it by calling it with the `new` operator. **webpack.config.js** ```javascript -const HtmlWebpackPlugin = require('html-webpack-plugin'); -const webpack = require('webpack'); //to access built-in plugins +import HtmlWebpackPlugin from 'html-webpack-plugin'; +import path from 'path'; //to access built-in plugins -module.exports = { +export default { module: { rules: [{ test: /\.txt$/, use: 'raw-loader' }], }, @@ -154,7 +154,7 @@ Using plugins in your webpack configuration is straightforward. However, there a By setting the `mode` parameter to either `development`, `production` or `none`, you can enable webpack's built-in optimizations that correspond to each environment. The default value is `production`. ```javascript -module.exports = { +export default { mode: 'production', }; ``` diff --git a/src/content/concepts/loaders.mdx b/src/content/concepts/loaders.mdx index 6c04910dd0a8..baf37e7224d5 100644 --- a/src/content/concepts/loaders.mdx +++ b/src/content/concepts/loaders.mdx @@ -34,7 +34,7 @@ And then instruct webpack to use the [`css-loader`](/loaders/css-loader) for eve **webpack.config.js** ```js -module.exports = { +export default { module: { rules: [ { test: /\.css$/, use: 'css-loader' }, @@ -61,7 +61,7 @@ This is a concise way to display loaders, and helps to maintain clean code. It a Loaders are evaluated/executed from right to left (or from bottom to top). In the example below execution starts with sass-loader, continues with css-loader and finally ends with style-loader. See ["Loader Features"](/concepts/loaders/#loader-features) for more information about loaders order. ```js -module.exports = { +export default { module: { rules: [ { diff --git a/src/content/concepts/module-federation.mdx b/src/content/concepts/module-federation.mdx index 82aa077ddcdf..792f2f4ef3fb 100644 --- a/src/content/concepts/module-federation.mdx +++ b/src/content/concepts/module-federation.mdx @@ -39,7 +39,7 @@ We distinguish between local and remote modules. Local modules are regular modul Loading remote modules is considered an asynchronous operation. When using a remote module, these asynchronous operations will be placed in the next chunk loading operation(s) that are between the remote module and the entrypoint. It's not possible to use a remote module without a chunk loading operation. -A chunk loading operation is usually an `import()` call, but older constructs like `require.ensure` or `require([...])` are supported as well. +A chunk loading operation is usually an `import()` call, but older constructs like `require.ensure` or `require([...])` were supported as well. A container is created through a container entry, which exposes asynchronous access to the specific modules. The exposed access is separated into two steps: @@ -156,7 +156,7 @@ loadComponent('abtests', 'test123'); Generally, remotes are configured using URL's like in this example: ```js -module.exports = { +export default { plugins: [ new ModuleFederationPlugin({ name: 'host', @@ -171,7 +171,7 @@ module.exports = { But you can also pass in a promise to this remote, which will be resolved at runtime. You should resolve this promise with any module that fits the `get/init` interface described above. For example, if you wanted to pass in which version of a federated module you should use, via a query parameter you could do something like the following: ```js -module.exports = { +export default { plugins: [ new ModuleFederationPlugin({ name: 'host', @@ -229,7 +229,7 @@ Example: **webpack.config.js (remote)** ```js -module.exports = { +export default { entry: { remote: './public-path', }, @@ -269,7 +269,7 @@ Example: **webpack.config.js (remote)** ```js -module.exports = { +export default { entry: { remote: './setup-public-path', }, diff --git a/src/content/concepts/output.mdx b/src/content/concepts/output.mdx index 71f599ccd84c..aebdee865c2e 100644 --- a/src/content/concepts/output.mdx +++ b/src/content/concepts/output.mdx @@ -18,7 +18,7 @@ The minimum requirement for the `output` property in your webpack configuration **webpack.config.js** ```javascript -module.exports = { +export default { output: { filename: 'bundle.js', }, @@ -32,14 +32,16 @@ This configuration would output a single `bundle.js` file into the `dist` direct If your configuration creates more than a single "chunk" (as with multiple entry points or when using plugins like CommonsChunkPlugin), you should use [substitutions](/configuration/output/#outputfilename) to ensure that each file has a unique name. ```javascript -module.exports = { +import path from 'path'; + +export default { entry: { app: './src/app.js', search: './src/search.js', }, output: { filename: '[name].js', - path: __dirname + '/dist', + path: path.resolve(__dirname, 'dist'), }, }; @@ -53,7 +55,7 @@ Here's a more complicated example of using a CDN and hashes for assets: **config.js** ```javascript -module.exports = { +export default { //... output: { path: '/home/proj/cdn/assets/[fullhash]', diff --git a/src/content/concepts/plugins.mdx b/src/content/concepts/plugins.mdx index b0d67294f969..10c189a8d0ca 100644 --- a/src/content/concepts/plugins.mdx +++ b/src/content/concepts/plugins.mdx @@ -15,7 +15,7 @@ contributors: They also serve the purpose of doing **anything else** that a [loader](/concepts/loaders) cannot do. Webpack provides [many such plugins](/plugins/) out of the box. -T> When consuming [`webpack-sources`](https://github.com/webpack/webpack-sources) package in plugins, use `require('webpack').sources` instead of `require('webpack-sources')` to avoid version conflicts for persistent caching. +T> When consuming [`webpack-sources`](https://github.com/webpack/webpack-sources) package in plugins, use `webpack.sources` instead of importing `webpack-sources` to avoid version conflicts for persistent caching. ## Anatomy @@ -34,7 +34,7 @@ class ConsoleLogOnBuildWebpackPlugin { } } -module.exports = ConsoleLogOnBuildWebpackPlugin; +export default ConsoleLogOnBuildWebpackPlugin; ``` It is recommended that the first parameter of the tap method of the compiler hook should be a camelized version of the plugin name. It is advisable to use a constant for this so it can be reused in all hooks. @@ -50,11 +50,11 @@ Depending on how you are using webpack, there are multiple ways to use plugins. **webpack.config.js** ```javascript -const HtmlWebpackPlugin = require('html-webpack-plugin'); -const webpack = require('webpack'); //to access built-in plugins -const path = require('path'); +import HtmlWebpackPlugin from 'html-webpack-plugin'; +import webpack from 'webpack'; //to access built-in plugins +import path from 'path'; -module.exports = { +export default { entry: './path/to/my/entry/file.js', output: { filename: 'my-first-webpack.bundle.js', @@ -84,8 +84,8 @@ When using the Node API, you can also pass plugins via the `plugins` property in **some-node-script.js** ```javascript -const webpack = require('webpack'); //to access webpack runtime -const configuration = require('./webpack.config.js'); +import webpack from 'webpack'; //to access webpack runtime +import configuration from './webpack.config.js'; let compiler = webpack(configuration); diff --git a/src/content/concepts/targets.mdx b/src/content/concepts/targets.mdx index 0e00b23451e2..80ebceb33a1a 100644 --- a/src/content/concepts/targets.mdx +++ b/src/content/concepts/targets.mdx @@ -21,7 +21,7 @@ To set the `target` property, you set the target value in your webpack config: **webpack.config.js** ```javascript -module.exports = { +export default { target: 'node', }; ``` @@ -39,7 +39,7 @@ Although webpack does **not** support multiple strings being passed into the `ta **webpack.config.js** ```javascript -const path = require('path'); +import path from 'path'; const serverConfig = { target: 'node', output: { @@ -58,7 +58,7 @@ const clientConfig = { //… }; -module.exports = [serverConfig, clientConfig]; +export default [serverConfig, clientConfig]; ``` The example above will create a `lib.js` and `lib.node.js` file in your `dist` folder. diff --git a/src/content/concepts/under-the-hood.mdx b/src/content/concepts/under-the-hood.mdx index f87221a9928a..24060e93d626 100644 --- a/src/content/concepts/under-the-hood.mdx +++ b/src/content/concepts/under-the-hood.mdx @@ -39,7 +39,7 @@ When you describe an entry point - under the hood, you create a chunk group with **./webpack.config.js** ```js -module.exports = { +export default { entry: './index.js', }; ``` @@ -52,7 +52,7 @@ Another example: **./webpack.config.js** ```js -module.exports = { +export default { entry: { home: './home.js', about: './about.js', @@ -77,7 +77,7 @@ Each chunk has a corresponding **asset**. The assets are the output files - the **webpack.config.js** ```js -module.exports = { +export default { entry: './src/index.jsx', }; ``` diff --git a/src/content/configuration/cache.mdx b/src/content/configuration/cache.mdx index e228dd66e4b9..a6ac6be44d09 100644 --- a/src/content/configuration/cache.mdx +++ b/src/content/configuration/cache.mdx @@ -15,7 +15,7 @@ Cache the generated webpack modules and chunks to improve build speed. `cache` i **webpack.config.js** ```javascript -module.exports = { +export default { //... cache: false, }; @@ -34,7 +34,7 @@ Collect unused memory allocated during deserialization, only available when [`ca **webpack.config.js** ```js -module.exports = { +export default { cache: { type: 'filesystem', allowCollectingMemory: true, @@ -55,7 +55,7 @@ T> It's recommended to set `cache.buildDependencies.config: [__filename]` in you **webpack.config.js** ```javascript -module.exports = { +export default { cache: { buildDependencies: { // This makes all dependencies of this file - build dependencies @@ -77,9 +77,9 @@ Base directory for the cache. Defaults to `node_modules/.cache/webpack`. **webpack.config.js** ```javascript -const path = require('path'); +import path from 'path'; -module.exports = { +export default { //... cache: { type: 'filesystem', @@ -99,9 +99,9 @@ Locations for the cache. Defaults to `path.resolve(cache.cacheDirectory, cache.n **webpack.config.js** ```javascript -const path = require('path'); +import path from 'path'; -module.exports = { +export default { //... cache: { type: 'filesystem', @@ -120,7 +120,7 @@ Cache computation of modules which are unchanged and reference only unchanged mo **webpack.config.js** ```javascript -module.exports = { +export default { //... cache: { type: 'memory', @@ -142,7 +142,7 @@ Compression type used for the cache files. By default it is `false`. **webpack.config.js** ```javascript -module.exports = { +export default { //... cache: { type: 'filesystem', @@ -162,7 +162,7 @@ Algorithm used the hash generation. See [Node.js crypto](https://nodejs.org/api/ **webpack.config.js** ```javascript -module.exports = { +export default { //... cache: { type: 'filesystem', @@ -182,7 +182,7 @@ Time in milliseconds. `cache.idleTimeout` denotes the time period after which th **webpack.config.js** ```javascript -module.exports = { +export default { //.. cache: { type: 'filesystem', @@ -204,7 +204,7 @@ Time in milliseconds. `cache.idleTimeoutAfterLargeChanges` is the time period af **webpack.config.js** ```javascript -module.exports = { +export default { //.. cache: { type: 'filesystem', @@ -224,7 +224,7 @@ Time in milliseconds. `cache.idleTimeoutForInitialStore` is the time period afte **webpack.config.js** ```javascript -module.exports = { +export default { //.. cache: { type: 'filesystem', @@ -254,7 +254,7 @@ The amount of time in milliseconds that unused cache entries are allowed to stay **webpack.config.js** ```javascript -module.exports = { +export default { // ... cache: { type: 'filesystem', @@ -280,7 +280,7 @@ Define the lifespan of unused cache entries in the memory cache. **webpack.config.js** ```javascript -module.exports = { +export default { // ... cache: { type: 'memory', @@ -310,7 +310,7 @@ Define the lifespan of unused cache entries in the memory cache. **webpack.config.js** ```javascript -module.exports = { +export default { // ... cache: { type: 'filesystem', @@ -329,7 +329,7 @@ Cache computation of modules which are unchanged and reference only unchanged mo **webpack.config.js** ```javascript -module.exports = { +export default { //... cache: { type: 'filesystem', @@ -349,7 +349,7 @@ Name for the cache. Different names will lead to different coexisting caches. De **webpack.config.js** ```javascript -module.exports = { +export default { //... cache: { type: 'filesystem', @@ -367,7 +367,7 @@ Track and log detailed timing information for individual cache items of type `'f **webpack.config.js** ```javascript -module.exports = { +export default { //... cache: { type: 'filesystem', @@ -383,7 +383,7 @@ module.exports = { Prevent webpack from storing cache into file system. Only available when `cache.type === "filesystem"` and `cache.store === 'pack'`. ```js -module.exports = { +export default { //... cache: { type: 'filesystem', @@ -408,7 +408,7 @@ W> `pack` is the only supported mode since webpack 5.0.x **webpack.config.js** ```javascript -module.exports = { +export default { //... cache: { type: 'filesystem', @@ -426,7 +426,7 @@ Sets the `cache` type to either in memory or on the file system. The `memory` op **webpack.config.js** ```javascript -module.exports = { +export default { //... cache: { type: 'memory', @@ -445,7 +445,7 @@ Version of the cache data. Different versions won't allow to reuse the cache and **webpack.config.js** ```javascript -module.exports = { +export default { //... cache: { type: 'filesystem', diff --git a/src/content/configuration/configuration-languages.mdx b/src/content/configuration/configuration-languages.mdx index 7f8052d4538b..726565e2694c 100644 --- a/src/content/configuration/configuration-languages.mdx +++ b/src/content/configuration/configuration-languages.mdx @@ -82,7 +82,7 @@ You can keep `"module": "ESNext"` for `tsc`, and if you use webpack, or another ```json { "compilerOptions": { - "module": "ESNext", + "module": "ESNext" }, "ts-node": { "compilerOptions": { @@ -141,9 +141,9 @@ and then proceed to write your configuration: **webpack.config.coffee** ```coffeescript -HtmlWebpackPlugin = require('html-webpack-plugin') -webpack = require('webpack') -path = require('path') +import HtmlWebpackPlugin from 'html-webpack-plugin' +import webpack from 'webpack' +import path from 'path' config = mode: 'production' @@ -159,7 +159,7 @@ config = new HtmlWebpackPlugin(template: './src/index.html') ] -module.exports = config +export default config ``` ## Babel and JSX @@ -211,4 +211,4 @@ export default ( ); ``` -W> If you are using Babel elsewhere and have `modules` set to `false`, you will have to either maintain two separate `.babelrc` files or use `const jsxobj = require('jsxobj');` and `module.exports` instead of the new `import` and `export` syntax. This is because while Node does support many new ES6 features, they don't yet support ES6 module syntax. +W> If you are using Babel elsewhere and have `modules` set to `false`, you will have to either maintain two separate Babel configurations to use the new `import` and `export` syntax. diff --git a/src/content/configuration/configuration-types.mdx b/src/content/configuration/configuration-types.mdx index 67409df31ec3..cea88a03c69f 100644 --- a/src/content/configuration/configuration-types.mdx +++ b/src/content/configuration/configuration-types.mdx @@ -24,8 +24,8 @@ Eventually you will find the need to disambiguate in your `webpack.config.js` be - An options map (`argv`) as the second parameter. This describes the options passed to webpack, with keys such as [`output-path`](/api/cli/#flags) and [`mode`](/api/cli/#flags). ```diff --module.exports = { -+module.exports = function(env, argv) { +-export default { ++export default function(env, argv) { + return { + mode: env.production ? 'production' : 'development', + devtool: env.production ? 'source-map' : 'eval', @@ -47,7 +47,7 @@ Webpack will run the function exported by the configuration file and wait for a T> It is possible to export multiple promises by wrapping them into `Promise.all([/* Your promises */]).` ```js -module.exports = () => { +export default () => { return new Promise((resolve, reject) => { setTimeout(() => { resolve({ @@ -66,7 +66,7 @@ W> Returning a `Promise` only works when using webpack via CLI. [`webpack()`](/a Instead of exporting a single configuration object/function, you may export multiple configurations (multiple functions are supported since webpack 3.1.0). When running webpack, all configurations are built. For instance, this is useful for [bundling a library](/guides/author-libraries) for multiple [targets](/configuration/output/#outputlibrarytarget) such as AMD and CommonJS: ```js -module.exports = [ +export default [ { output: { filename: './dist-amd.js', @@ -97,7 +97,7 @@ In case you have a configuration that depends on the output of another configura **webpack.config.js** ```js -module.exports = [ +export default [ { name: 'client', target: 'web', @@ -121,7 +121,8 @@ In case you export multiple configurations, you can use the `parallelism` option **webpack.config.js** ```javascript -module.exports = [ +export const parallelism = 1; +export default [ { //config-1 }, @@ -129,5 +130,4 @@ module.exports = [ //config-2 }, ]; -module.exports.parallelism = 1; ``` diff --git a/src/content/configuration/dev-server.mdx b/src/content/configuration/dev-server.mdx index c9d916348e09..52f851df47f8 100644 --- a/src/content/configuration/dev-server.mdx +++ b/src/content/configuration/dev-server.mdx @@ -40,9 +40,9 @@ This set of options is picked up by [webpack-dev-server](https://github.com/webp **webpack.config.js** ```javascript -const path = require('path'); +import path from 'path'; -module.exports = { +export default { //... devServer: { static: { @@ -103,9 +103,9 @@ Allows you to use custom server applications, such as `connect`, `fastify`, etc. **webpack.config.js** ```javascript -const connect = require('connect'); +import connect from 'connect'; -module.exports = { +export default { //... devServer: { app: () => connect(), @@ -122,7 +122,7 @@ This option allows you to allowlist services that are allowed to access the dev **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { allowedHosts: [ @@ -140,7 +140,7 @@ Mimicking Django's `ALLOWED_HOSTS`, a value beginning with `.` can be used as a **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { // this achieves the same effect as the first example @@ -162,7 +162,7 @@ When set to `'all'` this option bypasses host checking. **THIS IS NOT RECOMMENDE **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { allowedHosts: 'all', @@ -181,7 +181,7 @@ When set to `'auto'` this option always allows `localhost`, [`host`](#devserverh **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { allowedHosts: 'auto', @@ -204,7 +204,7 @@ This option broadcasts the server via [ZeroConf](http://www.zeroconf.org/) netwo **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { bonjour: true, @@ -229,7 +229,7 @@ You can also pass [custom options](https://github.com/watson/bonjour#initializin **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { bonjour: { @@ -251,7 +251,7 @@ Allows to set log level in the browser, e.g. before reloading, before an error o **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { client: { @@ -276,7 +276,7 @@ Shows a full-screen overlay in the browser when there are compiler errors or war **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { client: { @@ -313,7 +313,7 @@ For example, to disable compilation warnings, you can provide the following conf **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { client: { @@ -340,7 +340,7 @@ For example, to ignore errors thrown by [`AbortController.abort()`](https://deve **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { client: { @@ -368,7 +368,7 @@ Prints compilation progress in percentage in the browser. **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { client: { @@ -401,7 +401,7 @@ Tells dev-server the number of times it should try to reconnect the client. When **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { client: { @@ -420,7 +420,7 @@ npx webpack serve --client-reconnect When set to `false` it will not try to reconnect. ```javascript -module.exports = { +export default { //... devServer: { client: { @@ -439,7 +439,7 @@ npx webpack serve --no-client-reconnect You can also specify the exact number of times the client should try to reconnect. ```javascript -module.exports = { +export default { //... devServer: { client: { @@ -466,7 +466,7 @@ T> Providing `'ws'` or `'sockjs'` to [`webSocketServer`](#devserverwebsocketserv **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { client: { @@ -492,7 +492,8 @@ Using path to `CustomClient.js`, a custom WebSocket client implementation, along **webpack.config.js** ```javascript -module.exports = { +import path from 'path'; +export default { //... devServer: { client: { @@ -508,7 +509,8 @@ Using custom, compatible WebSocket client and server implementations: **webpack.config.js** ```javascript -module.exports = { +import path from 'path'; +export default { //... devServer: { client: { @@ -528,7 +530,7 @@ This option allows specifying URL to web socket server (useful when you're proxy **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { client: { @@ -556,7 +558,7 @@ You can also specify an object with the following properties: **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { client: { @@ -584,7 +586,7 @@ Enable [gzip compression](https://betterexplained.com/articles/how-to-optimize-y **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { compress: true, @@ -613,7 +615,7 @@ Provide options to [webpack-dev-middleware](https://github.com/webpack/webpack-d **webpack.config.js** ```javascript -module.exports = { +export default { devServer: { devMiddleware: { index: true, @@ -635,7 +637,7 @@ Adds headers to all responses: **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { headers: { @@ -650,7 +652,7 @@ You can also pass an array: **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { headers: [ @@ -670,7 +672,7 @@ module.exports = { You can also pass a function: ```javascript -module.exports = { +export default { //... devServer: { headers: () => { @@ -689,7 +691,7 @@ When using the [HTML5 History API](https://developer.mozilla.org/en-US/docs/Web/ **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { historyApiFallback: true, @@ -714,7 +716,7 @@ By providing an object this behavior can be controlled further using options lik **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { historyApiFallback: { @@ -733,7 +735,7 @@ When using dots in your path (common with Angular), you may need to use the `dis **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { historyApiFallback: { @@ -754,7 +756,7 @@ Specify a host to use. If you want your server to be accessible externally, spec **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { host: '0.0.0.0', @@ -807,7 +809,7 @@ Enable webpack's [Hot Module Replacement](/concepts/hot-module-replacement/) fea **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { hot: true, @@ -832,7 +834,7 @@ To enable Hot Module Replacement without page refresh as a fallback in case of b **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { hot: 'only', @@ -859,7 +861,7 @@ Setting it to `true` will listen to a socket at `/your-os-temp-dir/webpack-dev-s **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { ipc: true, @@ -878,9 +880,9 @@ You can also listen to a different socket with: **webpack.config.js** ```javascript -const path = require('path'); +import path from 'path'; -module.exports = { +export default { //... devServer: { ipc: path.join(__dirname, 'my-socket.sock'), @@ -897,7 +899,7 @@ By default, the dev-server will reload/refresh the page when file changes are de **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { liveReload: false, @@ -928,7 +930,7 @@ Provides the ability to execute a custom function when webpack-dev-server starts **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { onListening: function (devServer) { @@ -952,7 +954,7 @@ Tells dev-server to open the browser after server had been started. Set it to `t **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { open: true, @@ -977,7 +979,7 @@ To open a specified page in a browser: **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { open: ['/my-page'], @@ -996,7 +998,7 @@ To open multiple specified pages in browser: **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { open: ['/my-page', '/another-page'], @@ -1015,7 +1017,7 @@ Provide browser name to use instead of the default one: **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { open: { @@ -1038,7 +1040,7 @@ The object accepts all [open](https://www.npmjs.com/package/open) options: **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { open: { @@ -1063,7 +1065,7 @@ Specify a port number to listen for requests on: **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { port: 8080, @@ -1082,7 +1084,7 @@ npx webpack serve --port 8080 **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { port: 'auto', @@ -1109,7 +1111,7 @@ With a backend on `localhost:3000`, you can use this to enable proxying: **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { proxy: [ @@ -1129,7 +1131,7 @@ If you don't want `/api` to be passed along, we need to rewrite the path: **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { proxy: [ @@ -1148,7 +1150,7 @@ A backend server running on HTTPS with an invalid certificate will not be accept **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { proxy: [ @@ -1175,7 +1177,7 @@ E.g. for a browser request, you want to serve an HTML page, but for an API reque **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { proxy: [ @@ -1201,7 +1203,7 @@ If you want to proxy multiple, specific paths to the same target, you can use an **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { proxy: [ @@ -1219,7 +1221,7 @@ Note that requests to root won't be proxied by default. To enable root proxying, **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { devMiddleware: { @@ -1240,7 +1242,7 @@ The origin of the host header is kept when proxying by default, you can set `cha **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { proxy: [ @@ -1265,7 +1267,7 @@ Allows to set server and options (by default 'http'). **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { server: 'http', @@ -1284,7 +1286,7 @@ To serve over `HTTPS` with a self-signed certificate: **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { server: 'https', @@ -1303,7 +1305,7 @@ To serve over `HTTP/2` using [spdy](https://www.npmjs.com/package/spdy) with a s **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { server: 'spdy', @@ -1324,7 +1326,7 @@ Use the object syntax to provide your own certificate: **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { server: { @@ -1353,10 +1355,10 @@ It also allows you to set additional [TLS options](https://nodejs.org/api/tls.ht **webpack.config.js** ```javascript -const fs = require('fs'); -const path = require('path'); +import fs from 'fs'; +import path from 'path'; -module.exports = { +export default { //... devServer: { server: { @@ -1384,7 +1386,7 @@ Allows to close dev server and exit the process on `SIGINT` and `SIGTERM` signal **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { setupExitSignals: true, @@ -1403,7 +1405,7 @@ Provides the ability to execute a custom function and apply custom middleware(s) **webpack.config.js** ```javascript -module.exports = { +export default { // ... devServer: { setupMiddlewares: (middlewares, devServer) => { @@ -1456,7 +1458,7 @@ This option allows configuring options for serving static files from the directo **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { static: false, @@ -1481,7 +1483,7 @@ To watch a single directory: **webpack.config.js** ```js -module.exports = { +export default { // ... devServer: { static: ['assets'], @@ -1500,7 +1502,7 @@ To watch multiple static directories: **webpack.config.js** ```js -module.exports = { +export default { // ... devServer: { static: ['assets', 'css'], @@ -1523,9 +1525,9 @@ Tell the server where to serve the content from. This is only necessary if you w **webpack.config.js** ```javascript -const path = require('path'); +import path from 'path'; -module.exports = { +export default { //... devServer: { static: { @@ -1540,9 +1542,9 @@ Provide an array of objects in case you have multiple static folders: **webpack.config.js** ```javascript -const path = require('path'); +import path from 'path'; -module.exports = { +export default { //... devServer: { static: [ @@ -1568,7 +1570,7 @@ It is possible to configure advanced options for serving static files from [`sta **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { static: { @@ -1589,9 +1591,9 @@ Tell the server at which URL to serve [`static.directory`](#directory) content. **webpack.config.js** ```javascript -const path = require('path'); +import path from 'path'; -module.exports = { +export default { //... devServer: { static: { @@ -1607,9 +1609,9 @@ Provide an array of objects in case you have multiple static folders: **webpack.config.js** ```javascript -const path = require('path'); +import path from 'path'; -module.exports = { +export default { //... devServer: { static: [ @@ -1637,9 +1639,9 @@ Tell dev-server to use [`serveIndex`](https://github.com/expressjs/serve-index) **webpack.config.js** ```javascript -const path = require('path'); +import path from 'path'; -module.exports = { +export default { //... devServer: { static: { @@ -1671,9 +1673,9 @@ Tell dev-server to watch the files served by the [`static.directory`](#directory **webpack.config.js** ```javascript -const path = require('path'); +import path from 'path'; -module.exports = { +export default { //... devServer: { static: { @@ -1701,9 +1703,9 @@ It is possible to configure advanced options for watching static files from [`st **webpack.config.js** ```javascript -const path = require('path'); +import path from 'path'; -module.exports = { +export default { //... devServer: { static: { @@ -1726,7 +1728,7 @@ This option allows you to configure a list of globs/directories/files to watch f **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { watchFiles: ['src/**/*.php', 'public/**/*'], @@ -1739,7 +1741,7 @@ It is possible to configure advanced options for watching files. See the [`choki **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { watchFiles: { @@ -1763,7 +1765,7 @@ The current default mode is `'ws'`. This mode uses [`ws`](https://www.npmjs.com/ **webpack.config.js** ```javascript -module.exports = { +export default { //... devServer: { webSocketServer: 'ws', @@ -1778,13 +1780,14 @@ Using path to `CustomServer.js`, a custom WebSocket server implementation, along **webpack.config.js** ```javascript -module.exports = { +import path from 'path'; +export default { //... devServer: { client: { webSocketTransport: 'ws', }, - webSocketServer: require.resolve('./CustomServer'), + webSocketServer: path.resolve(__dirname, './CustomServer'), }, }; ``` @@ -1794,13 +1797,14 @@ Using custom, compatible WebSocket client and server implementations: **webpack.config.js** ```javascript -module.exports = { +import path from 'path'; +export default { //... devServer: { client: { - webSocketTransport: require.resolve('./CustomClient'), + webSocketTransport: path.resolve(__dirname, './CustomClient'), }, - webSocketServer: require.resolve('./CustomServer'), + webSocketServer: path.resolve(__dirname, './CustomServer'), }, }; ``` diff --git a/src/content/configuration/entry-context.mdx b/src/content/configuration/entry-context.mdx index 18e4187c7734..d9d1608f9bcf 100644 --- a/src/content/configuration/entry-context.mdx +++ b/src/content/configuration/entry-context.mdx @@ -23,9 +23,9 @@ The entry object is where webpack looks to start building the bundle. The contex The base directory, an **absolute path**, for resolving entry points and loaders from the configuration. ```js -const path = require('path'); +import path from 'path'; -module.exports = { +export default { //... context: path.resolve(__dirname, 'app'), }; @@ -46,7 +46,7 @@ A dynamically loaded module is **not** an entry point. A rule to consider: one entry point per HTML page. SPA: one entry point, MPA: multiple entry points. ```js -module.exports = { +export default { //... entry: { home: './home.js', @@ -65,7 +65,7 @@ If a string or array of strings is passed, the chunk is named `main`. If an obje If an object is passed the value might be a string, array of strings, or a descriptor: ```js -module.exports = { +export default { //... entry: { home: './home.js', @@ -95,7 +95,7 @@ Descriptor syntax might be used to pass additional options to an entry point. By default, the output filename for the entry chunk is extracted from [`output.filename`](/configuration/output/#outputfilename) but you can specify a custom output filename for a specific entry: ```js -module.exports = { +export default { //... entry: { app: './app.js', @@ -112,7 +112,7 @@ Descriptor syntax was used here to pass `filename`-option to the specific entry By default, every entry chunk stores all the modules that it uses. With `dependOn` option you can share the modules from one entry chunk to another: ```js -module.exports = { +export default { //... entry: { app: { import: './app.js', dependOn: 'react-vendors' }, @@ -126,7 +126,7 @@ The `app` chunk will not contain the modules that `react-vendors` have. `dependOn` option can also accept an array of strings: ```js -module.exports = { +export default { //... entry: { moment: { import: 'moment-mini', runtime: 'runtime' }, @@ -142,7 +142,7 @@ module.exports = { Also, you can specify multiple files per entry using an array: ```js -module.exports = { +export default { //... entry: { app: { import: ['./app.js', './app2.js'], dependOn: 'react-vendors' }, @@ -158,7 +158,7 @@ If a function is passed then it will be invoked on every [make](/api/compiler-ho > Note that the `make` event triggers when webpack starts and for every invalidation when [watching for file changes](/configuration/watch/). ```js -module.exports = { +export default { //... entry: () => './demo', }; @@ -167,7 +167,7 @@ module.exports = { or ```js -module.exports = { +export default { //... entry: () => new Promise((resolve) => resolve(['./demo', './demo2'])), }; @@ -178,7 +178,7 @@ For example: you can use dynamic entries to get the actual entries from an exter **webpack.config.js** ```js -module.exports = { +export default { entry() { return fetchPathsFromSomeExternalSource(); // returns a promise that will be resolved with something like ['src/main-layout.js', 'src/admin-layout.js'] }, @@ -194,7 +194,7 @@ It allows setting the runtime chunk for an entry point and setting it to `false` `optimization.runtimeChunk` allows setting it globally for unspecified entry points. ```js -module.exports = { +export default { //... entry: { home: { diff --git a/src/content/configuration/experiments.mdx b/src/content/configuration/experiments.mdx index dca8613267cc..ff14c4f047a7 100644 --- a/src/content/configuration/experiments.mdx +++ b/src/content/configuration/experiments.mdx @@ -36,7 +36,7 @@ Available options: **webpack.config.js** ```javascript -module.exports = { +export default { //... experiments: { asyncWebAssembly: true, @@ -56,7 +56,7 @@ Enable backward-compat layer with deprecation warnings for many webpack 4 APIs. - Type: `boolean` ```js -module.exports = { +export default { //... experiments: { backCompat: true, @@ -69,7 +69,6 @@ module.exports = { When enabled, webpack can build remote resources that begin with the `http(s):` protocol. - Type: - - `(string | RegExp | ((uri: string) => boolean))[]` A shortcut for [`experiments.buildHttp.allowedUris`](#experimentsbuildhttpalloweduris). @@ -91,7 +90,7 @@ When enabled, webpack can build remote resources that begin with the `http(s):` ```javascript // webpack.config.js - module.exports = { + export default { //... experiments: { buildHttp: true, @@ -115,7 +114,7 @@ A list of allowed URIs. ```javascript // webpack.config.js - module.exports = { + export default { //... experiments: { buildHttp: { @@ -139,7 +138,7 @@ Define the location for caching remote resources. ```javascript // webpack.config.js - module.exports = { + export default { //... experiments: { buildHttp: { @@ -265,7 +264,7 @@ Use defaults of the next major webpack and show warnings in any problematic plac **webpack.config.js** ```js -module.exports = { +export default { //... experiments: { futureDefaults: true, @@ -278,7 +277,6 @@ module.exports = { Compile entrypoints and dynamic `import`s only when they are in use. It can be used for either Web or Node.js. - Type - - `boolean` - `object` @@ -326,7 +324,7 @@ Compile entrypoints and dynamic `import`s only when they are in use. It can be u - Example 1: ```js - module.exports = { + export default { // … experiments: { lazyCompilation: true, @@ -337,7 +335,7 @@ Compile entrypoints and dynamic `import`s only when they are in use. It can be u - Example 2: ```js - module.exports = { + export default { // … experiments: { lazyCompilation: { @@ -361,7 +359,7 @@ Compile entrypoints and dynamic `import`s only when they are in use. It can be u Once enabled, webpack will output ECMAScript module syntax whenever possible. For instance, `import()` to load chunks, ESM exports to expose chunk data, among others. ```js -module.exports = { +export default { experiments: { outputModule: true, }, diff --git a/src/content/configuration/extending-configurations.mdx b/src/content/configuration/extending-configurations.mdx index 8d9e2dae11e5..2d58f36727d3 100644 --- a/src/content/configuration/extending-configurations.mdx +++ b/src/content/configuration/extending-configurations.mdx @@ -18,7 +18,7 @@ W> **This option is not supported via the Node API**: Extends will have no effec **base.webpack.config.js** ```javascript -module.exports = { +export default { module: { rules: [ { @@ -43,7 +43,12 @@ module.exports = { **webpack.config.js** ```javascript -module.exports = { +import path from 'path'; +import { fileURLToPath } from 'url'; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); + +export default { extends: path.resolve(__dirname, './base.webpack.config.js'), entry: './src/index.js', output: { @@ -62,7 +67,7 @@ Configurations from the `extends` property are merged from right to left, meanin **js.webpack.config.js** ```javascript -module.exports = { +export default { module: { rules: [ { @@ -78,7 +83,7 @@ module.exports = { **css.webpack.config.js** ```javascript -module.exports = { +export default { module: { rules: [ { @@ -93,7 +98,12 @@ module.exports = { **webpack.config.js** ```javascript -module.exports = { +import path from 'path'; +import { fileURLToPath } from 'url'; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); + +export default { extends: [ path.resolve(__dirname, './js.webpack.config.js'), path.resolve(__dirname, './css.webpack.config.js'), @@ -113,7 +123,7 @@ You can override configurations from the extended configuration by passing the s **base.webpack.config.js** ```javascript -module.exports = { +export default { output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js', @@ -124,7 +134,7 @@ module.exports = { **webpack.config.js** ```javascript -module.exports = { +export default { extends: path.resolve(__dirname, './base.webpack.config.js'), entry: './src/index.js', // overriding the output path and filename @@ -142,8 +152,8 @@ You can also load configuration from third-party packages by passing the package **webpack.config.js** ```javascript -module.exports = { - extends: require.resolve('webpack-config-foo'), +export default { + extends: import.meta.resolve('webpack-config-foo'), entry: './src/index.js', output: { path: path.resolve(__dirname, 'dist'), diff --git a/src/content/configuration/externals.mdx b/src/content/configuration/externals.mdx index 4515cb62f956..ba3da632d85b 100644 --- a/src/content/configuration/externals.mdx +++ b/src/content/configuration/externals.mdx @@ -45,7 +45,7 @@ For example, to include [jQuery](https://jquery.com/) from a CDN instead of bund **webpack.config.js** ```javascript -module.exports = { +export default { //... externals: { jquery: 'jQuery', @@ -72,7 +72,7 @@ Depending on the [externalsType](#externalstype), this could be the name of the You can also use the shortcut syntax if you're defining only 1 external: ```javascript -module.exports = { +export default { //... externals: 'jquery', }; @@ -81,7 +81,7 @@ module.exports = { equals to ```javascript -module.exports = { +export default { //... externals: { jquery: 'jquery', @@ -94,7 +94,7 @@ You can specify the [external library type](#externalstype) to the external with For example, if the external library is a [CommonJS module](#externalstypecommonjs), you can specify ```javascript -module.exports = { +export default { //... externals: { jquery: 'commonjs jquery', @@ -105,7 +105,7 @@ module.exports = { ### [string] ```javascript -module.exports = { +export default { //... externals: { subtract: ['./math', 'subtract'], @@ -120,7 +120,7 @@ When the `externalsType` is `commonjs`, this example would translate to `require Similar to the [string syntax](#string), you can specify the external library type with the `${externalsType} ${libraryName}` syntax, in the first item of the array, for example: ```javascript -module.exports = { +export default { //... externals: { subtract: ['commonjs ./math', 'subtract'], @@ -133,7 +133,7 @@ module.exports = { W> An object with `{ root, amd, commonjs, ... }` is only allowed for [`libraryTarget: 'umd'`](/configuration/output/#outputlibrarytarget) and [`externalsType: 'umd'`](#externalstype). It's not allowed for other library targets. ```javascript -module.exports = { +export default { //... externals: { react: 'react', @@ -188,7 +188,7 @@ As an example, to externalize all imports where the import path matches a regula **webpack.config.js** ```javascript -module.exports = { +export default { //... externals: [ function ({ context, request }, callback) { @@ -209,7 +209,7 @@ Other examples using different module formats: **webpack.config.js** ```javascript -module.exports = { +export default { externals: [ function (ctx, callback) { // The external is a `commonjs2` module located in `@scope/library` @@ -222,7 +222,7 @@ module.exports = { **webpack.config.js** ```javascript -module.exports = { +export default { externals: [ function (ctx, callback) { // The external is a global variable called `nameOfGlobal`. @@ -235,7 +235,7 @@ module.exports = { **webpack.config.js** ```javascript -module.exports = { +export default { externals: [ function (ctx, callback) { // The external is a named export in the `@scope/library` module. @@ -248,7 +248,7 @@ module.exports = { **webpack.config.js** ```javascript -module.exports = { +export default { externals: [ function (ctx, callback) { // The external is a UMD module @@ -270,7 +270,7 @@ Every dependency that matches the given regular expression will be excluded from **webpack.config.js** ```javascript -module.exports = { +export default { //... externals: /^(jquery|\$)$/i, }; @@ -285,7 +285,7 @@ Sometimes you may want to use a combination of the above syntaxes. This can be d **webpack.config.js** ```javascript -module.exports = { +export default { //... externals: [ { @@ -326,7 +326,7 @@ Specify externals by layer. **webpack.config.js** ```javascript -module.exports = { +export default { externals: { byLayer: { layer: { @@ -370,7 +370,7 @@ Supported types: **webpack.config.js** ```javascript -module.exports = { +export default { //... externalsType: 'promise', }; @@ -389,7 +389,7 @@ import fs from 'fs-extra'; **webpack.config.js** ```javascript -module.exports = { +export default { // ... externalsType: 'commonjs', externals: { @@ -401,10 +401,10 @@ module.exports = { Will generate into something like: ```javascript -const fs = require('fs-extra'); +import fs from 'fs-extra'; ``` -Note that there will be a `require()` in the output bundle. +Note that there will be a import in the output bundle. ### externalsType.global @@ -420,7 +420,7 @@ jq('.my-element').animate(/* ... */); **webpack.config.js** ```javascript -module.exports = { +export default { // ... externalsType: 'global', externals: { @@ -455,7 +455,7 @@ jq('.my-element').animate(/* ... */); **webpack.config.js** ```js -module.exports = { +export default { experiments: { outputModule: true, }, @@ -495,7 +495,7 @@ async function foo() { **webpack.config.js** ```js -module.exports = { +export default { externalsType: 'import', externals: { jquery: 'jquery', @@ -508,7 +508,7 @@ Will generate something like below: ```javascript var __webpack_modules__ = { jQuery: (module) => { - module.exports = import('jQuery'); + export default import('jQuery'); }, }; @@ -546,7 +546,7 @@ async function foo() { **webpack.config.js** ```js -module.exports = { +export default { externalsType: 'module-import', externals: { jquery: 'jquery', @@ -563,7 +563,7 @@ const lodash = __WEBPACK_EXTERNAL_MODULE_jquery__; var __webpack_modules__ = { jQuery: (module) => { - module.exports = import('jQuery'); + export default import('jQuery'); }, }; @@ -582,7 +582,7 @@ Note that the output bundle will have an `import` or `import()` statement. When a module is not imported via `import` or `import()`, webpack will use the `"module"` externals type as a fallback. If you want to use a different kind of externals as a fallback, you can specify it with a function in the `externals` option. For example: ```js -module.exports = { +export default { externalsType: "module-import", externals: [ function ( @@ -594,12 +594,12 @@ module.exports = { } callback(); }, - ] + ]} ``` ### externalsType.node-commonjs -Specify the default type of externals as `'node-commonjs'`. Webpack will import [`createRequire`](https://nodejs.org/api/module.html#module_module_createrequire_filename) from `'module'` to construct a require function for loading externals used in a module. +Specify the default type of externals as `'node-commonjs'`. Webpack will import [`createRequire`](https://nodejs.org/api/module.html#module_module_createrequire_filename) from `'module'` to construct a require function for loading externals used in a module.Webpack will import `createRequire` from `node:module` to construct a module loading function for loading externals used in a module. #### Example @@ -611,7 +611,7 @@ jq('.my-element').animate(/* ... */); **webpack.config.js** ```js -module.export = { +export default { experiments: { outputModule: true, }, @@ -647,9 +647,9 @@ util.inherits(ChunkStream, Stream); You can use `node-commonjs` to ensure that the prototype chain is preserved: ```js -const { builtinModules } = require('module'); +import { builtinModules } from 'module'; -module.exports = { +export default { experiments: { outputModule: true }, externalsType: 'node-commonjs', externals: ({ request }, callback) => { @@ -669,7 +669,7 @@ import { createRequire as __WEBPACK_EXTERNAL_createRequire } from "node:module"; /***/ 2613: /***/ ((module) => { -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("stream"); +export default __WEBPACK_EXTERNAL_createRequire(import.meta.url)("stream"); /***/ }), ``` @@ -690,7 +690,7 @@ jq('.my-element').animate(/* ... */); **webpack.config.js** ```javascript -module.exports = { +export default { // ... externalsType: 'promise', externals: { @@ -720,7 +720,7 @@ jq('.my-element').animate(/* ... */); **webpack.config.js** ```javascript -module.exports = { +export default { // ... externalsType: 'self', externals: { @@ -743,7 +743,7 @@ Specify the default type of externals as `'script'`. Webpack will load the exter #### Syntax ```javascript -module.exports = { +export default { externalsType: 'script', externals: { packageName: [ @@ -759,7 +759,7 @@ module.exports = { You can also use the shortcut syntax if you're not going to specify any properties: ```javascript -module.exports = { +export default { externalsType: 'script', externals: { packageName: 'global@http://example.com/script.js', // no properties here @@ -776,7 +776,7 @@ Let's load a `lodash` from CDN: **webpack.config.js** ```js -module.exports = { +export default { // ... externalsType: 'script', externals: { @@ -795,7 +795,7 @@ console.log(_.head([1, 2, 3])); Here's how we specify properties for the above example: ```js -module.exports = { +export default { // ... externalsType: 'script', externals: { @@ -834,7 +834,7 @@ jq('.my-element').animate(/* ... */); **webpack.config.js** ```javascript -module.exports = { +export default { // ... externalsType: 'this', externals: { @@ -864,7 +864,7 @@ jq('.my-element').animate(/* ... */); **webpack.config.js** ```javascript -module.exports = { +export default { // ... externalsType: 'var', externals: { @@ -894,7 +894,7 @@ jq('.my-element').animate(/* ... */); **webpack.config.js** ```javascript -module.exports = { +export default { // ... externalsType: 'window', externals: { @@ -918,25 +918,25 @@ Enable presets of externals for specific targets. | Option | Description | Input Type | | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | -| `electron` | Treat common electron built-in modules in main and preload context like `electron`, `ipc` or `shell` as external and load them via `require()` when used. | boolean | -| `electronMain` | Treat electron built-in modules in the main context like `app`, `ipc-main` or `shell` as external and load them via `require()` when used. | boolean | -| `electronPreload` | Treat electron built-in modules in the preload context like `web-frame`, `ipc-renderer` or `shell` as external and load them via require() when used. | boolean | -| `electronRenderer` | Treat electron built-in modules in the renderer context like `web-frame`, `ipc-renderer` or `shell` as external and load them via `require()` when used. | boolean | -| `node` | Treat node.js built-in modules like `fs`, `path` or `vm` as external and load them via `require()` when used. | boolean | -| `nwjs` | Treat `NW.js` legacy `nw.gui` module as external and load it via `require()` when used. | boolean | +| `electron` | Treat common electron built-in modules in main and preload context like `electron`, `ipc` or `shell` as external and load them via import when used. | boolean | +| `electronMain` | Treat electron built-in modules in the main context like `app`, `ipc-main` or `shell` as external and load them via import when used. | boolean | +| `electronPreload` | Treat electron built-in modules in the preload context like `web-frame`, `ipc-renderer` or `shell` as external and load them via import when used. | boolean | +| `electronRenderer` | Treat electron built-in modules in the renderer context like `web-frame`, `ipc-renderer` or `shell` as external and load them via import when used. | boolean | +| `node` | Treat node.js built-in modules like `fs`, `path` or `vm` as external and load them via import when used. | boolean | +| `nwjs` | Treat `NW.js` legacy `nw.gui` module as external and load it via import when used. | boolean | | `web` | Treat references to `http(s)://...` and `std:...` as external and load them via `import` when used. **(Note that this changes execution order as externals are executed before any other code in the chunk)**. | boolean | | `webAsync` | Treat references to `http(s)://...` and `std:...` as external and load them via `async import()` when used **(Note that this external type is an `async` module, which has various effects on the execution)**. | boolean | -Note that if you're going to output ES Modules with those node.js-related presets, webpack will set the default `externalsType` to [`node-commonjs`](#externalstypenode-commonjs) which would use `createRequire` to construct a require function instead of using `require()`. +Note that if you're going to output ES Modules with those node.js-related presets, webpack will set the default `externalsType` to [`node-commonjs`](#externalstypenode-commonjs) which would use `createRequire` to construct a require function instead of using import. **Example** -Using `node` preset will not bundle built-in modules and treats them as external and loads them via `require()` when used. +Using `node` preset will not bundle built-in modules and treats them as external and loads them via import when used. **webpack.config.js** ```js -module.exports = { +export default { // ... externalsPresets: { node: true, diff --git a/src/content/configuration/infrastructureLogging.mdx b/src/content/configuration/infrastructureLogging.mdx index 49790173c35c..6a1436b2b970 100644 --- a/src/content/configuration/infrastructureLogging.mdx +++ b/src/content/configuration/infrastructureLogging.mdx @@ -18,7 +18,7 @@ Append lines to the output instead of updating existing output, useful for statu **webpack.config.js** ```javascript -module.exports = { +export default { //... infrastructureLogging: { appendOnly: true, @@ -45,7 +45,7 @@ Enable colorful output for infrastructure level logging. This option is used onl **webpack.config.js** ```javascript -module.exports = { +export default { //... infrastructureLogging: { colors: true, @@ -71,7 +71,7 @@ Customize the console used for infrastructure level logging. **webpack.config.js** ```javascript -module.exports = { +export default { //... infrastructureLogging: { console: yourCustomConsole(), @@ -88,7 +88,7 @@ Enable debug information of specified loggers such as plugins or loaders. Simila **webpack.config.js** ```javascript -module.exports = { +export default { //... infrastructureLogging: { level: 'info', @@ -115,7 +115,7 @@ Possible values: **webpack.config.js** ```javascript -module.exports = { +export default { //... infrastructureLogging: { level: 'info', @@ -134,7 +134,7 @@ Stream used for logging output. Defaults to `process.stderr`. This option is use **webpack.config.js** ```javascript -module.exports = { +export default { //... infrastructureLogging: { stream: process.stderr, diff --git a/src/content/configuration/mode.mdx b/src/content/configuration/mode.mdx index 833f1c7d5b25..5434f5e467b2 100644 --- a/src/content/configuration/mode.mdx +++ b/src/content/configuration/mode.mdx @@ -22,7 +22,7 @@ Providing the `mode` configuration option tells webpack to use its built-in opti Provide the `mode` option in the config: ```javascript -module.exports = { +export default { mode: 'development', }; ``` @@ -49,7 +49,7 @@ T> If `mode` is not provided via configuration or CLI, CLI will use any valid `N ```js // webpack.development.config.js -module.exports = { +export default { mode: 'development', }; ``` @@ -58,7 +58,7 @@ module.exports = { ```js // webpack.production.config.js -module.exports = { +export default { mode: 'production', }; ``` @@ -67,7 +67,7 @@ module.exports = { ```js // webpack.custom.config.js -module.exports = { +export default { mode: 'none', }; ``` @@ -80,7 +80,7 @@ var config = { //... }; -module.exports = (env, argv) => { +export default (env, argv) => { if (argv.mode === 'development') { config.devtool = 'source-map'; } diff --git a/src/content/configuration/module.mdx b/src/content/configuration/module.mdx index 54a2ef184945..2ec0e82769ad 100644 --- a/src/content/configuration/module.mdx +++ b/src/content/configuration/module.mdx @@ -35,7 +35,7 @@ An array of rules applied by default for modules. See [source code](https://github.com/webpack/webpack/blob/dc4d97429b2013f7770ba785721b65cf82c2ef04/lib/config/defaults.js#L608) for details. ```js -module.exports = { +export default { module: { defaultRules: [ '...', // you can use "..." to reference those rules applied by webpack by default @@ -47,7 +47,7 @@ module.exports = { Starting with webpack 5.87.0, falsy values including `0`, `""`, `false`, `null` and `undefined` are allowed to pass to `module.defaultRules` to conditionally disable specific rules. ```js -module.exports = { +export default { module: { defaultRules: [ false && @@ -68,7 +68,7 @@ It's possible to configure all generators' options in one place with a `module.g **webpack.config.js** ```js -module.exports = { +export default { module: { generator: { asset: { @@ -211,7 +211,7 @@ Similar to the [`module.generator`](#modulegenerator), you can configure all par **webpack.config.js** ```js -module.exports = { +export default { module: { parser: { asset: { @@ -303,7 +303,7 @@ module.exports = { Configure options for the CSS parser. ```js -module.exports = { +export default { module: { parser: { css: { @@ -324,7 +324,7 @@ This option enables the handling of `@import` at-rules in CSS files. When set to - Example: ```js - module.exports = { + export default { module: { parser: { css: { @@ -363,7 +363,7 @@ This option enables the use of ES modules named export for CSS exports. When set - Example: ```js - module.exports = { + export default { module: { parser: { css: { @@ -416,7 +416,7 @@ This option enables or disables the handling of URLs in functions such as `url() - Example: ```js - module.exports = { + export default { module: { parser: { css: { @@ -445,7 +445,7 @@ T> To filter specific imports, you can use Webpack's built-in [IgnorePlugin](/pl Configure options for JavaScript parser. ```js -module.exports = { +export default { module: { parser: { javascript: { @@ -468,7 +468,7 @@ Enable [magic comments](/api/module-methods/#magic-comments) support for CommonJ - Example: ```js - module.exports = { + export default { module: { parser: { javascript: { @@ -494,7 +494,7 @@ Specify the global [fetchPriority](https://developer.mozilla.org/en-US/docs/Web/ - Example: ```js - module.exports = { + export default { module: { parser: { javascript: { @@ -514,7 +514,7 @@ Specifies global mode for dynamic import. - Example: ```js - module.exports = { + export default { module: { parser: { javascript: { @@ -534,7 +534,7 @@ Specifies global prefetch for dynamic import. - Example: ```js - module.exports = { + export default { module: { parser: { javascript: { @@ -554,7 +554,7 @@ Specifies global preload for dynamic import. - Example: ```js - module.exports = { + export default { module: { parser: { javascript: { @@ -574,7 +574,7 @@ Specifies the behavior of invalid export names in `\"import ... from ...\"` and - Example: ```js - module.exports = { + export default { module: { parser: { javascript: { @@ -594,7 +594,7 @@ Specifies the behavior of invalid export names in `\"import ... from ...\"`. - Example: ```js - module.exports = { + export default { module: { parser: { javascript: { @@ -614,7 +614,7 @@ Enable or disable evaluating `import.meta`. - Example: ```js - module.exports = { + export default { module: { parser: { javascript: { @@ -634,7 +634,7 @@ Enable/disable evaluating [`import.meta.webpackContext`](/api/module-variables/# - Example: ```js - module.exports = { + export default { module: { parser: { javascript: { @@ -654,7 +654,7 @@ Set the module to `'strict'` or `'non-strict'` mode. This can affect the module' - Example: ```js - module.exports = { + export default { module: { parser: { javascript: { @@ -674,7 +674,7 @@ Specifies the behavior of invalid export names in `\"export ... from ...\"`. Thi - Example: ```js - module.exports = { + export default { module: { parser: { javascript: { @@ -693,7 +693,7 @@ Enable parsing of `new URL()` syntax. - Example: ```js - module.exports = { + export default { module: { parser: { javascript: { @@ -722,7 +722,7 @@ The `'relative'` value for `module.parser.javascript.url` is available since web Configure options for json parser. ```js -module.exports = { +export default { module: { parser: { json: { @@ -742,7 +742,7 @@ The depth of json dependency flagged as `exportInfo`. By default, it is set to ` - Example: ```js -module.exports = { +export default { module: { parser: { json: { @@ -777,7 +777,7 @@ T> You may need to use `[\\/]` in regex to match `\` on Windows and `/` on Mac/L **webpack.config.js** ```javascript -module.exports = { +export default { //... module: { noParse: /jquery|lodash|src[\\/]vendor[\\/]somelib/, @@ -786,7 +786,7 @@ module.exports = { ``` ```javascript -module.exports = { +export default { //... module: { noParse: (content) => @@ -807,7 +807,7 @@ Cache the resolution of module requests. There are a couple of defaults for `mod **webpack.config.js** ```javascript -module.exports = { +export default { //... module: { unsafeCache: false, @@ -881,7 +881,8 @@ A [`Condition`](#condition) that allows you to match the import assertion of a d **webpack.config.js** ```javascript -module.exports = { +import path from 'path'; +export default { // ... module: { rules: [ @@ -910,7 +911,7 @@ A [`Condition`](#condition) that allows you to match the child compiler name. **webpack.config.js** ```javascript -module.exports = { +export default { // ... name: 'compiler', module: { @@ -991,7 +992,7 @@ Allows to filter/match by layer of the issuer. **webpack.config.js** ```js -module.exports = { +export default { // ... module: { rules: [ @@ -1012,7 +1013,7 @@ Specify the layer in which the module should be placed in. A group of modules co **webpack.config.js** ```js -module.exports = { +export default { // ... module: { rules: [ @@ -1034,7 +1035,7 @@ Extracts existing source map data from files (from their `//# sourceMappingURL` **webpack.config.js** ```js -module.exports = { +export default { // ... module: { rules: [ @@ -1064,7 +1065,7 @@ You can match config rules to data uri with `mimetype`. **webpack.config.js** ```js -module.exports = { +export default { // ... module: { rules: [ @@ -1086,7 +1087,7 @@ An array of [`Rules`](#rule) from which only the first matching Rule is used whe **webpack.config.js** ```javascript -module.exports = { +export default { //... module: { rules: [ @@ -1130,7 +1131,7 @@ However, parser plugins may accept more than only a boolean. For example, the in **Examples** (parser options by the default plugins): ```js -module.exports = { +export default { //... module: { rules: [ @@ -1141,9 +1142,9 @@ module.exports = { commonjs: false, // disable CommonJS system: false, // disable SystemJS harmony: false, // disable ES2015 Harmony import/export - requireInclude: false, // disable require.include - requireEnsure: false, // disable require.ensure - requireContext: false, // disable require.context + //requireInclude: false, // disable require.include + //requireEnsure: false, // disable require.ensure + //requireContext: false, // disable require.context browserify: false, // disable special handling of Browserify bundles requireJs: false, // disable requirejs.* node: false, // disable __dirname, __filename, module, require.extensions, require.main, etc. @@ -1172,7 +1173,7 @@ If a module source size is less than `maxSize` then module will be injected into **webpack.config.js** ```js -module.exports = { +export default { //... module: { rules: [ @@ -1194,7 +1195,7 @@ When a function is given, returning `true` tells webpack to inject the module in **webpack.config.js** ```js -module.exports = { +export default { //... module: { rules: [ @@ -1226,7 +1227,7 @@ When `Rule.generator.dataUrl` is used as an object, you can configure two proper **webpack.config.js** ```js -module.exports = { +export default { //... module: { rules: [ @@ -1247,7 +1248,7 @@ module.exports = { When used as a function, it executes for every module and must return a data URI string. ```js -module.exports = { +export default { //... module: { rules: [ @@ -1255,7 +1256,7 @@ module.exports = { //... generator: { dataUrl: (content) => { - const svgToMiniDataURI = require('mini-svg-data-uri'); + const svgToMiniDataURI = (info) => info; if (typeof content !== 'string') { content = content.toString(); } @@ -1277,7 +1278,7 @@ Opt out of writing assets from [Asset Modules](/guides/asset-modules/), you migh - Example: ```js - module.exports = { + export default { // … module: { rules: [ @@ -1300,7 +1301,7 @@ The same as [`output.assetModuleFilename`](/configuration/output/#outputassetmod **webpack.config.js** ```js -module.exports = { +export default { //... output: { assetModuleFilename: 'images/[hash][ext][query]', @@ -1331,7 +1332,7 @@ Customize `publicPath` for specific Asset Modules. - Available: ```js -module.exports = { +export default { //... output: { publicPath: 'static/', @@ -1358,7 +1359,7 @@ Emit the asset in the specified folder relative to 'output.path'. This should on - Available: ```js -module.exports = { +export default { //... output: { publicPath: 'static/', @@ -1389,7 +1390,7 @@ A [`Condition`](#condition) matched with the resource query. This option is used **webpack.config.js** ```javascript -module.exports = { +export default { //... module: { rules: [ @@ -1412,9 +1413,9 @@ If `Rule.type` is set to `'json'` then `Rules.parser.parse` option may be a func **webpack.config.js** ```javascript -const toml = require('toml'); +import toml from 'toml'; -module.exports = { +export default { //... module: { rules: [ @@ -1446,7 +1447,7 @@ Match the used schema, e.g., `data`, `http`. **webpack.config.js** ```js -module.exports = { +export default { module: { rules: [ { @@ -1479,7 +1480,7 @@ Possible values: `'javascript/auto' | 'javascript/dynamic' | 'javascript/esm' | **webpack.config.js** ```javascript -module.exports = { +export default { //... module: { rules: [ @@ -1503,7 +1504,7 @@ module.exports = { See use case of `css/auto` module type [here](https://github.com/webpack/webpack/issues/16572). Make sure to enable [`experiments.css`](/configuration/experiments/#experimentscss) to use `css/auto`. ```js -module.exports = { +export default { target: 'web', mode: 'development', experiments: { @@ -1538,7 +1539,7 @@ Loaders can be chained by passing multiple loaders, which will be applied from r **webpack.config.js** ```javascript -module.exports = { +export default { //... module: { rules: [ @@ -1581,7 +1582,7 @@ The same shortcut as an array can be used for the return value (i.e. `use: [ 'st **webpack.config.js** ```javascript -module.exports = { +export default { //... module: { rules: [ @@ -1642,7 +1643,7 @@ export default 'overridden footer'; **webpack.js.org** ```javascript -module.exports = { +export default { resolve: { alias: { footer: './footer/default.js', @@ -1656,7 +1657,7 @@ When creating a bundle with this configuration, `console.log(footer)` will outpu **webpack.js.org** ```javascript -module.exports = { +export default { resolve: { alias: { footer: './footer/default.js', @@ -1687,7 +1688,7 @@ When enabled, you should provide the file extension when `import`ing a module in **webpack.config.js** ```js -module.exports = { +export default { // ... module: { rules: [ @@ -1713,7 +1714,8 @@ A [`Condition`](#condition) that allows you to match the imports based on specif **webpack.config.js** ```javascript -module.exports = { +import path from 'path'; +export default { // ... module: { rules: [ @@ -1754,9 +1756,9 @@ Conditions can be one of these: **Example:** ```javascript -const path = require('path'); +import path from 'path'; -module.exports = { +export default { //... module: { rules: [ @@ -1794,7 +1796,7 @@ It also breaks if the options object cannot be stringified (i.e. circular JSON). **webpack.config.js** ```javascript -module.exports = { +export default { //... module: { rules: [ @@ -1823,7 +1825,7 @@ The `info` object parameter has the following fields: **webpack.config.js** ```javascript -module.exports = { +export default { //... module: { rules: [ @@ -1850,18 +1852,18 @@ module.exports = { These options describe the default settings for the context created when a dynamic dependency is encountered. -Example for an `unknown` dynamic dependency: `require`. +Example for an `unknown` dynamic dependency: `import`. -Example for an `expr` dynamic dependency: `require(expr)`. +Example for an `expr` dynamic dependency: `import(expr)`. -Example for an `wrapped` dynamic dependency: `require('./templates/' + expr)`. +Example for an `wrapped` dynamic dependency: `import('./templates/' + expr)`. Here are the available options with their [defaults](https://github.com/webpack/webpack/blob/main/lib/config/defaults.js): **webpack.config.js** ```javascript -module.exports = { +export default { //... module: { exprContextCritical: true, @@ -1885,8 +1887,8 @@ T> You can use the `ContextReplacementPlugin` to modify these values for individ A few use cases: - Warn for dynamic dependencies: `wrappedContextCritical: true`. -- `require(expr)` should include the whole directory: `exprContextRegExp: /^\.\//` -- `require('./templates/' + expr)` should not include subdirectories by default: `wrappedContextRecursive: false` +- `import(expr)` should include the whole directory: `exprContextRegExp: /^\.\//` +- `import('./templates/' + expr)` should not include subdirectories by default: `wrappedContextRecursive: false` - `strictExportPresence` makes missing exports an error instead of warning - Set the inner regular expression for partial dynamic dependencies : `wrappedContextRegExp: /\\.\\*/` diff --git a/src/content/configuration/node.mdx b/src/content/configuration/node.mdx index 703eca62fff4..ee302098841c 100644 --- a/src/content/configuration/node.mdx +++ b/src/content/configuration/node.mdx @@ -26,7 +26,7 @@ W> As of webpack 5, You can configure only `global`, `__filename` or `__dirname` **webpack.config.js** ```javascript -module.exports = { +export default { //... node: { global: false, diff --git a/src/content/configuration/optimization.mdx b/src/content/configuration/optimization.mdx index 7256d4eb759b..a9d2f6d71775 100644 --- a/src/content/configuration/optimization.mdx +++ b/src/content/configuration/optimization.mdx @@ -31,7 +31,7 @@ Tells webpack to check the incompatible types of WebAssembly modules when they a **webpack.config.js** ```js -module.exports = { +export default { //... optimization: { checkWasmTypes: false, @@ -61,7 +61,7 @@ The following string values are supported: **webpack.config.js** ```js -module.exports = { +export default { //... optimization: { chunkIds: 'named', @@ -74,7 +74,7 @@ By default, a minimum length of 3 digits is used when `optimization.chunkIds` is **webpack.config.js** ```js -module.exports = { +export default { //... optimization: { chunkIds: false, @@ -97,7 +97,7 @@ By default `optimization.concatenateModules` is enabled in `production` [mode](/ **webpack.config.js** ```js -module.exports = { +export default { //... optimization: { concatenateModules: true, @@ -114,7 +114,7 @@ Use the `optimization.emitOnErrors` to emit assets whenever there are errors whi **webpack.config.js** ```js -module.exports = { +export default { //... optimization: { emitOnErrors: true, @@ -139,7 +139,7 @@ By default, `optimization.avoidEntryIife` is enabled in `production` [mode](/con **webpack.config.js** ```js -module.exports = { +export default { //... optimization: { avoidEntryIife: true, @@ -158,7 +158,7 @@ Tells webpack to determine and flag chunks which are subsets of other chunks in **webpack.config.js** ```js -module.exports = { +export default { //... optimization: { flagIncludedChunks: true, @@ -175,7 +175,7 @@ module.exports = { **webpack.config.js** ```js -module.exports = { +export default { //... optimization: { innerGraph: false, @@ -203,7 +203,7 @@ The following values are supported: **webpack.config.js** ```js -module.exports = { +export default { //... optimization: { mangleExports: true, @@ -220,7 +220,7 @@ When set to `true` tells webpack to reduce the size of WASM by changing imports **webpack.config.js** ```js -module.exports = { +export default { //... optimization: { mangleWasmImports: true, @@ -237,7 +237,7 @@ Tells webpack to merge chunks which contain the same modules. Setting `optimizat **webpack.config.js** ```js -module.exports = { +export default { //... optimization: { mergeDuplicateChunks: false, @@ -254,7 +254,7 @@ Tell webpack to minimize the bundle using the [TerserPlugin](/plugins/terser-web **webpack.config.js** ```js -module.exports = { +export default { //... optimization: { minimize: false, @@ -273,9 +273,9 @@ Allows you to override the default minimizer by providing a different one or mor **webpack.config.js** ```js -const TerserPlugin = require('terser-webpack-plugin'); +import TerserPlugin from 'terser-webpack-plugin'; -module.exports = { +export default { optimization: { minimizer: [ new TerserPlugin({ @@ -292,11 +292,10 @@ module.exports = { Or, as function: ```js -module.exports = { +export default { optimization: { minimizer: [ (compiler) => { - const TerserPlugin = require('terser-webpack-plugin'); new TerserPlugin({ /* your config */ }).apply(compiler); @@ -313,7 +312,6 @@ By default, webpack would set `optimization.minimizer` to [the following value]( { apply: (compiler) => { // Lazy load the Terser plugin - const TerserPlugin = require('terser-webpack-plugin'); new TerserPlugin({ terserOptions: { compress: { @@ -329,7 +327,7 @@ By default, webpack would set `optimization.minimizer` to [the following value]( Which can be accessed with `'...'` in case you want to keep it when customizing `optimization.minimizer`: ```js -module.exports = { +export default { optimization: { minimizer: [new CssMinimizer(), '...'], }, @@ -356,7 +354,7 @@ The following string values are supported: **webpack.config.js** ```js -module.exports = { +export default { //... optimization: { moduleIds: 'deterministic', @@ -369,7 +367,7 @@ module.exports = { **webpack.config.js** ```js -module.exports = { +export default { //... optimization: { moduleIds: false, @@ -400,7 +398,7 @@ Possible values: **webpack.config.js** ```js -module.exports = { +export default { //... optimization: { nodeEnv: 'production', @@ -421,7 +419,7 @@ By default `optimization.portableRecords` is disabled. Automatically enabled if **webpack.config.js** ```js -module.exports = { +export default { //... optimization: { portableRecords: true, @@ -438,7 +436,7 @@ Tells webpack to figure out which exports are provided by modules to generate mo **webpack.config.js** ```js -module.exports = { +export default { //... optimization: { providedExports: false, @@ -455,7 +453,7 @@ Adds an additional hash compilation pass after the assets have been processed to **webpack.config.js** ```js -module.exports = { +export default { //... optimization: { realContentHash: false, @@ -472,7 +470,7 @@ Tells webpack to detect and remove modules from chunks when these modules are al **webpack.config.js** ```js -module.exports = { +export default { //... optimization: { removeAvailableModules: true, @@ -491,7 +489,7 @@ Tells webpack to detect and remove chunks which are empty. Setting `optimization **webpack.config.js** ```js -module.exports = { +export default { //... optimization: { removeEmptyChunks: false, @@ -508,7 +506,7 @@ Setting `optimization.runtimeChunk` to `true` or `'multiple'` adds an additional **webpack.config.js** ```js -module.exports = { +export default { //... optimization: { runtimeChunk: { @@ -523,7 +521,7 @@ The value `'single'` instead creates a runtime file to be shared for all generat **webpack.config.js** ```js -module.exports = { +export default { //... optimization: { runtimeChunk: { @@ -542,7 +540,7 @@ W> Imported modules are initialized for each runtime chunk separately, so if you **webpack.config.js** ```js -module.exports = { +export default { //... optimization: { runtimeChunk: { @@ -575,7 +573,7 @@ T> Please note that `sideEffects` should be in the npm module's `package.json` f **webpack.config.js** ```js -module.exports = { +export default { //... optimization: { sideEffects: true, @@ -586,7 +584,7 @@ module.exports = { To only use the manual flag and do not analyse source code: ```js -module.exports = { +export default { //... optimization: { sideEffects: 'flag', @@ -614,7 +612,7 @@ Dead code elimination in minimizers will benefit from this and can remove unused **webpack.config.js** ```js -module.exports = { +export default { //... optimization: { usedExports: false, @@ -625,7 +623,7 @@ module.exports = { To opt-out from used exports analysis per runtime: ```js -module.exports = { +export default { //... optimization: { usedExports: 'global', diff --git a/src/content/configuration/other-options.mdx b/src/content/configuration/other-options.mdx index b1104e634f3b..aef6a4aadf52 100644 --- a/src/content/configuration/other-options.mdx +++ b/src/content/configuration/other-options.mdx @@ -30,12 +30,12 @@ W> Help Wanted: This page is still a work in progress. If you are familiar with `object` `boolean: false` -Set the value of `require.amd` or `define.amd`. Setting `amd` to `false` will disable webpack's AMD support. +Set the value of `import.amd` or `define.amd`. Setting `amd` to `false` will disable webpack's AMD support. **webpack.config.js** ```javascript -module.exports = { +export default { //... amd: { jQuery: true, @@ -59,7 +59,7 @@ Fail out on the first error instead of tolerating it. By default webpack will lo **webpack.config.js** ```javascript -module.exports = { +export default { //... bail: true, }; @@ -85,7 +85,7 @@ Remember that current configuration will not compile until its dependencies are **webpack.config.js** ```js -module.exports = [ +export default [ { name: 'client', target: 'web', @@ -112,7 +112,7 @@ Tells webpack to ignore specific warnings. This can be done with a `RegExp`, a c `ignoreWarnings` must be an `array` of any or all of the above. ```javascript -module.exports = { +export default { //... ignoreWarnings: [ { @@ -139,7 +139,7 @@ For example, you can define a new variable in the loader context: **webpack.config.js** ```javascript -module.exports = { +export default { // ... loader: { answer: 42, @@ -152,11 +152,11 @@ Then use `this.answer` to get its value in the loader: **custom-loader.js** ```javascript -module.exports = function (source) { +export default function (source) { // ... console.log(this.answer); // will log `42` here return source; -}; +} ``` T> You can override properties in the loader context as webpack copies all properties that are defined in the `loader` to the loader context. @@ -170,7 +170,7 @@ Name of the configuration. Used when loading multiple configurations. **webpack.config.js** ```javascript -module.exports = { +export default { //... name: 'admin-app', }; @@ -205,9 +205,9 @@ Specify where the records should be written. The following example shows how you **webpack.config.js** ```javascript -const path = require('path'); +import path from 'path'; -module.exports = { +export default { //... recordsInputPath: path.join(__dirname, 'records.json'), recordsOutputPath: path.join(__dirname, 'newRecords.json'), @@ -223,9 +223,9 @@ Use this option to generate a JSON file containing webpack "records" – pieces **webpack.config.js** ```javascript -const path = require('path'); +import path from 'path'; -module.exports = { +export default { //... recordsPath: path.join(__dirname, 'records.json'), }; @@ -246,8 +246,8 @@ W> Setting `recordsPath` will essentially set `recordsInputPath` and `recordsOut **webpack.config.js** ```javascript -const path = require('path'); -module.exports = { +import path from 'path'; +export default { // ... snapshot: { managedPaths: [path.resolve(__dirname, '../node_modules')], @@ -313,7 +313,7 @@ Make sure you wrap the path in a capture group if you are using regular expressi A common use case for `managedPaths` would be to exclude some folders from `node_modules`, e.g. you want webpack to know that files in the `node_modules/@azure/msal-browser` folder are expected to change, which can be done with a regular expression like the one below: ```js -module.exports = { +export default { snapshot: { managedPaths: [ /^(.+?[\\/]node_modules[\\/](?!(@azure[\\/]msal-browser))(@.+?[\\/])?.+?)[\\/]/, @@ -350,7 +350,6 @@ Snapshots for building context modules. - `hash`: Compare content hashes to determine invalidation (more expensive than `timestamp`, but changes less often). - `timestamp`: Compare timestamps to determine invalidation. - ### resolve `object = {hash boolean = true, timestamp boolean = true}` diff --git a/src/content/configuration/output.mdx b/src/content/configuration/output.mdx index 81b9f9e356de..d9f3dde16943 100644 --- a/src/content/configuration/output.mdx +++ b/src/content/configuration/output.mdx @@ -52,7 +52,7 @@ Create async chunks that are loaded on demand. **webpack.config.js** ```javascript -module.exports = { +export default { //... output: { //... @@ -72,7 +72,7 @@ When used in tandem with [`output.library`](#outputlibrary) and [`output.library **webpack.config.js** ```javascript -module.exports = { +export default { //... output: { library: 'someLibName', @@ -91,16 +91,14 @@ which will yield the following: (function webpackUniversalModuleDefinition(root, factory) { // Test Comment if (typeof exports === 'object' && typeof module === 'object') - module.exports = factory(require('lodash')); + export default factory(); // Test Comment - else if (typeof define === 'function' && define.amd) - define(['lodash'], factory); + else if (typeof define === 'function' && define.amd) define([], factory); // Test Comment - else if (typeof exports === 'object') - exports['someLibName'] = factory(require('lodash')); + else if (typeof exports === 'object') exports['someLibName'] = factory(); // Test Comment - else root['someLibName'] = factory(root['_']); -})(this, function (__WEBPACK_EXTERNAL_MODULE_1__) { + else root['someLibName'] = factory(); +})(this, function () { // ... }); ``` @@ -110,7 +108,7 @@ For fine-grained control over each `libraryTarget` comment, pass an object: **webpack.config.js** ```javascript -module.exports = { +export default { //... output: { //... @@ -145,7 +143,7 @@ By default `[id].js` is used or a value inferred from [`output.filename`](#outpu **webpack.config.js** ```javascript -module.exports = { +export default { //... output: { //... @@ -159,7 +157,7 @@ Usage as a function: **webpack.config.js** ```javascript -module.exports = { +export default { //... output: { chunkFilename: (pathData) => { @@ -182,7 +180,7 @@ T> The default value of this option depends on the [`target`](/configuration/tar **webpack.config.js** ```javascript -module.exports = { +export default { //... output: { //... @@ -200,7 +198,7 @@ The Number of milliseconds before chunk request expires. This option is supporte **webpack.config.js** ```javascript -module.exports = { +export default { //... output: { //... @@ -218,7 +216,7 @@ The global variable is used by webpack for loading chunks. **webpack.config.js** ```javascript -module.exports = { +export default { //... output: { //... @@ -231,14 +229,14 @@ module.exports = { `false` `string: 'jsonp' | 'import-scripts' | 'require' | 'async-node' | 'import' | ` -The method to load chunks (methods included by default are `'jsonp'` (web), `'import'` (ESM), `'importScripts'` (WebWorker), `'require'` (sync node.js), `'async-node'` (async node.js), but others might be added by plugins). +The method to load chunks (methods included by default are `'jsonp'` (web), `'import'` (ESM), `'importScripts'` (WebWorker), 'node-commonjs' (sync node.js), `'async-node'` (async node.js), but others might be added by plugins). T> The default value of this option depends on the [`target`](/configuration/target/) and [`chunkFormat `](#outputchunkformat) setting. For more details, search for `"chunkLoading"` [in the webpack defaults](https://github.com/webpack/webpack/blob/main/lib/config/defaults.js). **webpack.config.js** ```javascript -module.exports = { +export default { //... output: { //... @@ -254,7 +252,7 @@ module.exports = { `boolean` `{ dry?: boolean, keep?: RegExp | string | ((filename: string) => boolean) }` ```javascript -module.exports = { +export default { //... output: { clean: true, // Clean the output directory before emit. @@ -263,7 +261,7 @@ module.exports = { ``` ```javascript -module.exports = { +export default { //... output: { clean: { @@ -274,7 +272,7 @@ module.exports = { ``` ```javascript -module.exports = { +export default { //... output: { clean: { @@ -285,7 +283,7 @@ module.exports = { // or -module.exports = { +export default { //... output: { clean: { @@ -317,7 +315,7 @@ Tells webpack to check if to be emitted file already exists and has the same con W> webpack will not write output file when file already exists on disk with the same content. ```javascript -module.exports = { +export default { //... output: { compareBeforeEmit: false, @@ -369,7 +367,7 @@ Customize the names used in each source map's `sources` array. This can be done **webpack.config.js** ```javascript -module.exports = { +export default { //... output: { devtoolModuleFilenameTemplate: @@ -394,7 +392,7 @@ The following substitutions are available in template strings (via webpack's int When using a function, the same options are available camel-cased via the `info` parameter: ```javascript -module.exports = { +export default { //... output: { devtoolModuleFilenameTemplate: (info) => { @@ -419,7 +417,7 @@ You can use template strings like `[name]` to dynamically generate namespaces ba **webpack.config.js** ```javascript -module.exports = { +export default { //... output: { filename: '[name]-bundle.js', @@ -439,11 +437,11 @@ List of chunk loading types enabled for use by entry points. Will be automatical **webpack.config.js** ```javascript -module.exports = { +export default { //... output: { //... - enabledChunkLoadingTypes: ['jsonp', 'require'], + enabledChunkLoadingTypes: ['jsonp', 'node-commonjs'], }, }; ``` @@ -455,7 +453,7 @@ module.exports = { List of library types enabled for use by entry points. ```javascript -module.exports = { +export default { //... output: { enabledLibraryTypes: ['module'], @@ -470,7 +468,7 @@ module.exports = { List of wasm loading types enabled for use by entry points. ```javascript -module.exports = { +export default { //... output: { enabledWasmLoadingTypes: ['fetch'], @@ -483,7 +481,7 @@ module.exports = { Tell webpack what kind of ES-features may be used in the generated runtime-code. ```javascript -module.exports = { +export default { output: { environment: { // The environment supports arrow functions ('() => { ... }'). @@ -531,7 +529,7 @@ For a single [`entry`](/configuration/entry-context/#entry) point, this can be a **webpack.config.js** ```javascript -module.exports = { +export default { //... output: { filename: 'bundle.js', @@ -546,7 +544,7 @@ Using entry name: **webpack.config.js** ```javascript -module.exports = { +export default { //... output: { filename: '[name].bundle.js', @@ -559,7 +557,7 @@ Using internal chunk id: **webpack.config.js** ```javascript -module.exports = { +export default { //... output: { filename: '[id].bundle.js', @@ -572,7 +570,7 @@ Using hashes generated from the generated content: **webpack.config.js** ```javascript -module.exports = { +export default { //... output: { filename: '[contenthash].bundle.js', @@ -585,7 +583,7 @@ Combining multiple substitutions: **webpack.config.js** ```javascript -module.exports = { +export default { //... output: { filename: '[name].[contenthash].bundle.js', @@ -598,7 +596,7 @@ Using the function to return the filename: **webpack.config.js** ```javascript -module.exports = { +export default { //... output: { filename: (pathData) => { @@ -719,7 +717,7 @@ For example: **webpack.config.js** ```javascript -module.exports = { +export default { // ... output: { library: { @@ -753,10 +751,11 @@ T> For `webpack v5.65.0+`, `16` will be used as the default value for the `hashD The hashing algorithm to use. All functions from Node.JS' [`crypto.createHash`](https://nodejs.org/api/crypto.html#crypto_crypto_createhash_algorithm_options) are supported. Since `4.0.0-alpha2`, the `hashFunction` can now be a constructor to a custom hash function. You can provide a non-crypto hash function for performance reasons. ```javascript -module.exports = { +import { MetroHash64 } from 'metrohash'; +export default { //... output: { - hashFunction: require('metrohash').MetroHash64, + hashFunction: MetroHash64, }, }; ``` @@ -780,7 +779,7 @@ The only placeholders allowed here are `[id]` and `[fullhash]`, the default bein **webpack.config.js** ```javascript -module.exports = { +export default { //... output: { hotUpdateChunkFilename: '[id].[fullhash].hot-update.js', @@ -815,7 +814,7 @@ T> Typically you don't need to change `output.hotUpdateMainFilename`. Tells webpack to add [IIFE](https://developer.mozilla.org/en-US/docs/Glossary/IIFE) wrapper around emitted code. ```javascript -module.exports = { +export default { //... output: { iife: true, @@ -834,7 +833,7 @@ Hide warnings from the browser console in production. This option does not affec **webpack.config.js** ```javascript -module.exports = { +export default { //... output: { ignoreBrowserWarnings: true, @@ -851,7 +850,7 @@ The name of the native `import()` function. Can be used for polyfilling, e.g. wi **webpack.config.js** ```javascript -module.exports = { +export default { //... output: { importFunctionName: '__import__', @@ -868,7 +867,7 @@ The name of the native `import.meta` object (can be exchanged for a polyfill). **webpack.config.js** ```javascript -module.exports = { +export default { //... output: { importMetaName: 'pseudoImport.meta', @@ -887,7 +886,7 @@ Let's take a look at an example. **webpack.config.js** ```js -module.exports = { +export default { // … entry: './src/index.js', output: { @@ -918,7 +917,7 @@ In the above example, we're passing a single entry file to `entry`, however, web 1. If you provide an `array` as the `entry` point, only the last one in the array will be exposed. ```js - module.exports = { + export default { // … entry: ['./src/a.js', './src/b.js'], // only exports in b.js will be exposed output: { @@ -930,7 +929,7 @@ In the above example, we're passing a single entry file to `entry`, however, web 2. If an `object` is provided as the `entry` point, all entries can be exposed using the `array` syntax of `library`: ```js - module.exports = { + export default { // … entry: { a: './src/a.js', @@ -959,7 +958,7 @@ In the above example, we're passing a single entry file to `entry`, however, web Note that the above configuration won't work as expected if you're going to configure library options per entry point. Here is how to do it [under each of your entries](/concepts/entry-points/#entrydescription-object): ```js - module.exports = { + export default { // … entry: { main: { @@ -991,7 +990,7 @@ Use a container(defined in global space) for calling `define`/`require` function W> Note that the value of `amdContainer` **must be** set as a global variable. ```js -module.exports = { +export default { // … output: { library: { @@ -1011,7 +1010,7 @@ window['clientContainer'].define(/*define args*/); // or 'amd-require' window['c ### output.library.name ```js -module.exports = { +export default { // … output: { library: { @@ -1046,7 +1045,7 @@ These options assign the return value of the entry point (e.g. whatever the entr ##### type: 'var' ```js -module.exports = { +export default { // … output: { library: { @@ -1069,7 +1068,7 @@ MyLibrary.doSomething(); ##### type: 'assign' ```js -module.exports = { +export default { // … output: { library: { @@ -1093,7 +1092,7 @@ Be aware that if `MyLibrary` isn't defined earlier your library will be set in g ```js -module.exports = { +export default { // … output: { library: { @@ -1129,7 +1128,7 @@ These options assign the return value of the entry point (e.g. whatever the entr ##### type: 'this' ```js -module.exports = { +export default { // … output: { library: { @@ -1153,7 +1152,7 @@ MyLibrary.doSomething(); // if `this` is window ##### type: 'window' ```js -module.exports = { +export default { // … output: { library: { @@ -1175,7 +1174,7 @@ window.MyLibrary.doSomething(); ##### type: 'global' ```js -module.exports = { +export default { // … output: { library: { @@ -1197,7 +1196,7 @@ global.MyLibrary.doSomething(); ##### type: 'commonjs' ```js -module.exports = { +export default { // … output: { library: { @@ -1225,7 +1224,7 @@ These options will result in a bundle that comes with a complete header to ensur ##### type: 'module' ```js -module.exports = { +export default { // … experiments: { outputModule: true, @@ -1248,7 +1247,7 @@ However this feature is still experimental and not fully supported yet, so make ```js -module.exports = { +export default { // … experiments: { outputModule: true, @@ -1269,7 +1268,7 @@ However this feature is still experimental and not fully supported yet, so make ##### type: 'commonjs2' ```js -module.exports = { +export default { // … output: { library: { @@ -1283,7 +1282,7 @@ module.exports = { The **return value of your entry point** will be assigned to the `module.exports`. As the name implies, this is used in Node.js (CommonJS) environments: ```javascript -module.exports = _entry_return_; +export default _entry_return_; require('MyLibrary').doSomething(); ``` @@ -1301,7 +1300,7 @@ T> Wondering the difference between CommonJS and CommonJS2 is? While they are si ```js -module.exports = { +export default { // … output: { library: { @@ -1353,7 +1352,7 @@ AMD modules require that the entry chunk (e.g. the first script loaded by the `< With the following configuration... ```javascript -module.exports = { +export default { //... output: { library: { @@ -1393,7 +1392,7 @@ This bundle will not work as expected, or not work at all (in the case of the al ##### type: 'amd-require' ```javascript -module.exports = { +export default { //... output: { library: { @@ -1417,7 +1416,7 @@ This exposes your library under all the module definitions, allowing it to work In this case, you need the `library.name` property to name your module: ```javascript -module.exports = { +export default { //... output: { library: { @@ -1433,7 +1432,7 @@ And finally the output is: ```javascript (function webpackUniversalModuleDefinition(root, factory) { if (typeof exports === 'object' && typeof module === 'object') - module.exports = factory(); + export default factory(); else if (typeof define === 'function' && define.amd) define([], factory); else if (typeof exports === 'object') exports['MyLibrary'] = factory(); else root['MyLibrary'] = factory(); @@ -1445,7 +1444,7 @@ And finally the output is: Note that omitting `library.name` will result in the assignment of all properties returned by the entry point be assigned directly to the root object, as documented under the [object assignment section](#expose-via-object-assignment). Example: ```javascript -module.exports = { +export default { //... output: { type: 'umd', @@ -1458,7 +1457,7 @@ The output will be: ```javascript (function webpackUniversalModuleDefinition(root, factory) { if (typeof exports === 'object' && typeof module === 'object') - module.exports = factory(); + export default factory(); else if (typeof define === 'function' && define.amd) define([], factory); else { var a = factory(); @@ -1472,7 +1471,7 @@ The output will be: You may specify an object for `library.name` for differing names per targets: ```javascript -module.exports = { +export default { //... output: { library: { @@ -1494,7 +1493,7 @@ This will expose your library as a [`System.register`](https://github.com/system System modules require that a global variable `System` is present in the browser when the webpack bundle is executed. Compiling to `System.register` format allows you to `System.import('/bundle.js')` without additional configuration and has your webpack bundle loaded into the System module registry. ```javascript -module.exports = { +export default { //... output: { library: { @@ -1537,7 +1536,7 @@ System.register( ##### type: 'jsonp' ```js -module.exports = { +export default { // … output: { library: { @@ -1567,7 +1566,7 @@ Specify which export should be exposed as a library. It is `undefined` by default, which will export the whole (namespace) object. The examples below demonstrate the effect of this configuration when using [`output.library.type: 'var'`](#type-var). ```js -module.exports = { +export default { output: { library: { name: 'MyLibrary', @@ -1588,7 +1587,7 @@ var MyLibrary = _entry_return_.default; You can pass an array to `output.library.export` as well, it will be interpreted as a path to a module to be assigned to the library name: ```js -module.exports = { +export default { output: { library: { name: 'MyLibrary', @@ -1614,7 +1613,7 @@ Add a comment in the UMD wrapper. To insert the same comment for each `umd` type, set `auxiliaryComment` to a string: ```js -module.exports = { +export default { // … mode: 'development', output: { @@ -1633,7 +1632,7 @@ which will yield the following: (function webpackUniversalModuleDefinition(root, factory) { //Test Comment if (typeof exports === 'object' && typeof module === 'object') - module.exports = factory(); + export default factory(); //Test Comment else if (typeof define === 'function' && define.amd) define([], factory); //Test Comment @@ -1648,7 +1647,7 @@ which will yield the following: For fine-grained control, pass an object: ```js -module.exports = { +export default { // … mode: 'development', output: { @@ -1673,7 +1672,7 @@ module.exports = { When using `output.library.type: "umd"`, setting `output.library.umdNamedDefine` to `true` will name the AMD module of the UMD build. Otherwise, an anonymous `define` is used. ```javascript -module.exports = { +export default { //... output: { library: { @@ -1878,7 +1877,7 @@ W> Prefer to use [`output.library.type: 'commonjs2'`](#type-commonjs2). The **return value of your entry point** will be assigned to the `module.exports`. As the name implies, this is used in CommonJS environments: ```javascript -module.exports = _entry_return_; +export default _entry_return_; require('MyLibrary').doSomething(); ``` @@ -1898,7 +1897,7 @@ AMD modules require that the entry chunk (e.g. the first script loaded by the `< With the following configuration... ```javascript -module.exports = { +export default { //... output: { library: 'MyLibrary', @@ -1952,7 +1951,7 @@ This exposes your library under all the module definitions, allowing it to work In this case, you need the `library` property to name your module: ```javascript -module.exports = { +export default { //... output: { library: 'MyLibrary', @@ -1966,7 +1965,7 @@ And finally the output is: ```javascript (function webpackUniversalModuleDefinition(root, factory) { if (typeof exports === 'object' && typeof module === 'object') - module.exports = factory(); + export default factory(); else if (typeof define === 'function' && define.amd) define([], factory); else if (typeof exports === 'object') exports['MyLibrary'] = factory(); else root['MyLibrary'] = factory(); @@ -1978,7 +1977,7 @@ And finally the output is: Note that omitting the `library` will result in the assignment of all properties returned by the entry point be assigned directly to the root object, as documented under the [object assignment section](#expose-via-object-assignment). Example: ```javascript -module.exports = { +export default { //... output: { libraryTarget: 'umd', @@ -1991,7 +1990,7 @@ The output will be: ```javascript (function webpackUniversalModuleDefinition(root, factory) { if (typeof exports === 'object' && typeof module === 'object') - module.exports = factory(); + export default factory(); else if (typeof define === 'function' && define.amd) define([], factory); else { var a = factory(); @@ -2005,7 +2004,7 @@ The output will be: Since webpack 3.1.0, you may specify an object for `library` for differing names per targets: ```javascript -module.exports = { +export default { //... output: { library: { @@ -2027,7 +2026,7 @@ This will expose your library as a [`System.register`](https://github.com/system System modules require that a global variable `System` is present in the browser when the webpack bundle is executed. Compiling to `System.register` format allows you to `System.import('/bundle.js')` without additional configuration and has your webpack bundle loaded into the System module registry. ```javascript -module.exports = { +export default { //... output: { libraryTarget: 'system', @@ -2098,7 +2097,7 @@ When enabled, webpack will set [`output.iife`](#outputiife) to `false`, [`output If you're using webpack to compile a library to be consumed by others, make sure to set [`output.libraryTarget`](#librarytarget-module) to `'module'` when `output.module` is `true`. ```javascript -module.exports = { +export default { //... experiments: { outputModule: true, @@ -2120,9 +2119,9 @@ The output directory as an **absolute** path. **webpack.config.js** ```javascript -const path = require('path'); +import path from 'path'; -module.exports = { +export default { //... output: { path: path.resolve(__dirname, 'dist/assets'), @@ -2145,7 +2144,7 @@ W> While the data these comments can provide is useful during development when r **webpack.config.js** ```javascript -module.exports = { +export default { //... output: { pathinfo: true, @@ -2158,7 +2157,6 @@ T> It also adds some info about tree shaking to the generated bundle. ## output.publicPath - Type: - - `function` - `string` @@ -2175,9 +2173,9 @@ A rule to consider: The URL of your [`output.path`](#outputpath) from the view o **webpack.config.js** ```javascript -const path = require('path'); +import path from 'path'; -module.exports = { +export default { //... output: { path: path.resolve(__dirname, 'public/assets'), @@ -2191,7 +2189,7 @@ For this configuration: **webpack.config.js** ```javascript -module.exports = { +export default { //... output: { publicPath: '/assets/', @@ -2221,7 +2219,7 @@ Note that `[fullhash]` in this parameter will be replaced with a hash of the com Examples: ```javascript -module.exports = { +export default { //... output: { // One of the below @@ -2255,7 +2253,7 @@ This option allows loading asynchronous chunks with a custom script type, such a T> If [`output.module`](#outputmodule) is set to `true`, `output.scriptType` will default to `'module'` instead of `false`. ```javascript -module.exports = { +export default { //... output: { scriptType: 'module', @@ -2280,7 +2278,7 @@ Change the prefix for each line in the output bundles. **webpack.config.js** ```javascript -module.exports = { +export default { //... output: { sourcePrefix: '\t', @@ -2300,7 +2298,7 @@ Handle error in module loading as per EcmaScript Modules spec at a performance c - Available: 5.25.0+ ```javascript -module.exports = { +export default { //... output: { strictModuleErrorHandling: true, @@ -2315,11 +2313,11 @@ W> Deprecated, use `boolean = false` -Tell webpack to remove a module from the module instance cache (`require.cache`) if it throws an exception when it is `require`d. +Tell webpack to remove a module from the module instance cache if it throws an exception when it is `import`ed. It defaults to `false` for performance reasons. -When set to `false`, the module is not removed from cache, which results in the exception getting thrown only on the first `require` call (making it incompatible with node.js). +When set to `false`, the module is not removed from cache, which results in the exception getting thrown only on the first `import` call (making it incompatible with modern EcmaScript environments). For instance, consider `module.js`: @@ -2327,20 +2325,20 @@ For instance, consider `module.js`: throw new Error('error'); ``` -With `strictModuleExceptionHandling` set to `false`, only the first `require` throws an exception: +With `strictModuleExceptionHandling` set to `false`, only the first `import` throws an exception: ```javascript // with strictModuleExceptionHandling = false -require('module'); // <- throws -require('module'); // <- doesn't throw +// In a non-strict environment (CommonJS legacy): +// First import throws, second does not (due to non-removal from cache). ``` -Instead, with `strictModuleExceptionHandling` set to `true`, all `require`s of this module throw an exception: +Instead, with `strictModuleExceptionHandling` set to `true`, all `import`s of this module throw an exception: ```javascript // with strictModuleExceptionHandling = true -require('module'); // <- throws -require('module'); // <- also throws +// In a strict environment (consistent with ESM): +// Both imports throw (module is removed from cache after exception). ``` ## output.trustedTypes @@ -2360,7 +2358,7 @@ It is disabled by default (no compatibility, script URLs are strings). **webpack.config.js** ```javascript -module.exports = { +export default { //... output: { //... @@ -2380,7 +2378,7 @@ module.exports = { Determine whether to proceed with loading in anticipation that [`require-trusted-types-for 'script'`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/require-trusted-types-for) has not been enforced or to immediately fail when the call to `trustedTypes.createPolicy(...)` fails due to the policy name being absent from the CSP `trusted-types` list or being a duplicate. ```javascript -module.exports = { +export default { //... output: { //... @@ -2401,7 +2399,7 @@ W> Prefer to use [`output.library.umdNamedDefine`](#outputlibraryumdnameddefine) When using `libraryTarget: "umd"`, setting `output.umdNamedDefine` to `true` will name the AMD module of the UMD build. Otherwise an anonymous `define` is used. ```javascript -module.exports = { +export default { //... output: { umdNamedDefine: true, @@ -2422,7 +2420,7 @@ A unique name of the webpack build to avoid multiple webpack runtimes to conflic **webpack.config.js** ```javascript -module.exports = { +export default { // ... output: { uniqueName: 'my-package-xyz', @@ -2442,7 +2440,7 @@ The default value can be affected by different [`target`](/configuration/target/ - Defaults to `'async-node'` if [`target`](/configuration/target/) is set to `'node'`, `'async-node'`, `'electron-main'` or `'electron-preload'`. ```javascript -module.exports = { +export default { //... output: { wasmLoading: 'fetch', @@ -2457,7 +2455,7 @@ module.exports = { Specifies the filename of WebAssembly modules. It should be provided as a relative path within the `output.path` directory ```javascript -module.exports = { +export default { //... output: { webassemblyModuleFilename: '[id].[hash].wasm', @@ -2467,7 +2465,7 @@ module.exports = { ## output.workerChunkLoading -`string: 'require' | 'import-scripts' | 'async-node' | 'import' | 'universal'` `boolean: false` +`string: 'node-commonjs'| 'import-scripts' | 'async-node' | 'import' | 'universal'` `boolean: false` The new option `workerChunkLoading` controls the chunk loading of workers. @@ -2476,7 +2474,7 @@ T> The default value of this option depends on the [`target`](/configuration/tar **webpack.config.js** ```javascript -module.exports = { +export default { //... output: { workerChunkLoading: false, @@ -2493,7 +2491,7 @@ Set a public path for Worker, defaults to value of [output.publicPath](#outputpu **webpack.config.js** ```javascript -module.exports = { +export default { //... output: { workerPublicPath: '/workerPublicPath2/', @@ -2510,7 +2508,7 @@ Option to set the method of loading WebAssembly Modules in workers, defaults to **webpack.config.js** ```javascript -module.exports = { +export default { //... output: { workerWasmLoading: 'fetch', diff --git a/src/content/configuration/performance.mdx b/src/content/configuration/performance.mdx index 7db08fd31036..eff56e04c6ac 100644 --- a/src/content/configuration/performance.mdx +++ b/src/content/configuration/performance.mdx @@ -33,7 +33,7 @@ function assetFilter(assetFilename) { You can override this property by passing your own function in: ```js -module.exports = { +export default { //... performance: { assetFilter: function (assetFilename) { @@ -54,7 +54,7 @@ Turns hints on/off. In addition, tells webpack to throw either an error or a war Given an asset is created that is over 250kb: ```js -module.exports = { +export default { //... performance: { hints: false, @@ -65,7 +65,7 @@ module.exports = { No hint warnings or errors are shown. ```js -module.exports = { +export default { //... performance: { hints: 'warning', @@ -76,7 +76,7 @@ module.exports = { A warning will be displayed notifying you of a large asset. We recommend something like this for development environments. ```js -module.exports = { +export default { //... performance: { hints: 'error', @@ -93,7 +93,7 @@ An error will be displayed notifying you of a large asset. We recommend using `h An asset is any emitted file from webpack. This option controls when webpack emits a performance hint based on individual asset size in bytes. ```js -module.exports = { +export default { //... performance: { maxAssetSize: 100000, @@ -108,7 +108,7 @@ module.exports = { An entry point represents all assets that would be utilized during initial load time for a specific entry. This option controls when webpack should emit performance hints based on the maximum entry point size in bytes. ```js -module.exports = { +export default { //... performance: { maxEntrypointSize: 400000, diff --git a/src/content/configuration/plugins.mdx b/src/content/configuration/plugins.mdx index 721f56090af4..944599089e76 100644 --- a/src/content/configuration/plugins.mdx +++ b/src/content/configuration/plugins.mdx @@ -23,7 +23,7 @@ An array of webpack plugins. For example, [`DefinePlugin`](/plugins/define-plugi **webpack.config.js** ```js -module.exports = { +export default { //... plugins: [ new webpack.DefinePlugin({ @@ -39,12 +39,12 @@ A more complex example, using multiple plugins, might look something like this: **webpack.config.js** ```js -var webpack = require('webpack'); +import webpack from 'webpack'; // importing plugins that do not come by default in webpack -var DashboardPlugin = require('webpack-dashboard/plugin'); +import DashboardPlugin from 'webpack-dashboard/plugin'; // adding plugins to your configuration -module.exports = { +export default { //... plugins: [ new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/), diff --git a/src/content/configuration/resolve.mdx b/src/content/configuration/resolve.mdx index 6b15ecd23bc7..d3e33479e4b8 100644 --- a/src/content/configuration/resolve.mdx +++ b/src/content/configuration/resolve.mdx @@ -32,7 +32,7 @@ Configure how modules are resolved. For example, when calling `import 'lodash'` **webpack.config.js** ```js -module.exports = { +export default { //... resolve: { // configuration options @@ -49,9 +49,9 @@ Create aliases to `import` or `require` certain modules more easily. For example **webpack.config.js** ```js -const path = require('path'); +import path from 'path'; -module.exports = { +export default { //... resolve: { alias: { @@ -79,9 +79,9 @@ A trailing `$` can also be added to the given object's keys to signify an exact **webpack.config.js** ```js -const path = require('path'); +import path from 'path'; -module.exports = { +export default { //... resolve: { alias: { @@ -103,7 +103,8 @@ You can also use wildcards (`*`) in your alias configuration to create more flex **webpack.config.js** ```js -module.exports = { +import path from 'path'; +export default { //... resolve: { alias: { @@ -149,7 +150,7 @@ W> [`null-loader`](https://github.com/webpack-contrib/null-loader) is deprecated W> `[string]` values are supported since webpack 5. ```js -module.exports = { +export default { //... resolve: { alias: { @@ -165,7 +166,7 @@ module.exports = { Setting `resolve.alias` to `false` will tell webpack to ignore a module. ```js -module.exports = { +export default { //... resolve: { alias: { @@ -185,7 +186,7 @@ Specify a field, such as `browser`, to be parsed according to [this specificatio **webpack.config.js** ```js -module.exports = { +export default { //... resolve: { aliasFields: ['browser'], @@ -201,7 +202,7 @@ Configure resolve options by the type of module request. - Example: ```js - module.exports = { + export default { // ... resolve: { byDependency: { @@ -229,7 +230,7 @@ Enables caching of successfully resolved requests, allowing cache entries to be **webpack.config.js** ```js -module.exports = { +export default { //... resolve: { cache: true, @@ -246,7 +247,7 @@ A function which decides whether a request should be cached or not. An object is **webpack.config.js** ```js -module.exports = { +export default { //... resolve: { cachePredicate: (module) => { @@ -272,7 +273,7 @@ Condition names for [`exports` field](https://nodejs.org/api/packages.html#packa **webpack.config.js** ```js -module.exports = { +export default { //... resolve: { conditionNames: ['require', 'node'], @@ -312,7 +313,7 @@ For example, **webpack.config.js** ```js -module.exports = { +export default { //... resolve: { conditionNames: ['require', 'node'], @@ -331,7 +332,7 @@ If you want to add your custom field names while still retaining the default Web **webpack.config.js** ```js -module.exports = { +export default { //... resolve: { conditionNames: ['my-custom-condition', '...'], @@ -344,7 +345,7 @@ Alternatively, to prioritize the default conditions first, then add your custom **webpack.config.js** ```js -module.exports = { +export default { //... resolve: { conditionNames: ['...', 'my-custom-condition'], @@ -361,7 +362,7 @@ The JSON files to use for descriptions. **webpack.config.js** ```js -module.exports = { +export default { //... resolve: { descriptionFiles: ['package.json'], @@ -378,7 +379,7 @@ If `true`, it will not allow extension-less files. So by default `require('./foo **webpack.config.js** ```js -module.exports = { +export default { //... resolve: { enforceExtension: false, @@ -395,7 +396,7 @@ Fields in package.json that are used for resolving module requests. See [package **webpack.config.js** ```js -module.exports = { +export default { //... resolve: { exportsFields: ['exports', 'myCompanyExports'], @@ -412,7 +413,7 @@ An object which maps extension to extension aliases. **webpack.config.js** ```js -module.exports = { +export default { //... resolve: { extensionAlias: { @@ -432,7 +433,7 @@ Attempt to resolve these extensions in order. If multiple files share the same n **webpack.config.js** ```js -module.exports = { +export default { //... resolve: { extensions: ['.js', '.json', '.wasm'], @@ -449,7 +450,7 @@ import File from '../path/to/file'; Note that using `resolve.extensions` like above will **override the default array**, meaning that webpack will no longer try to resolve modules using the default extensions. However you can use `'...'` to access the default extensions: ```js -module.exports = { +export default { //... resolve: { extensions: ['.ts', '...'], @@ -466,7 +467,7 @@ Redirect module requests when normal resolving fails. **webpack.config.js** ```js -module.exports = { +export default { //... resolve: { fallback: { @@ -480,33 +481,33 @@ module.exports = { Webpack 5 no longer polyfills Node.js core modules automatically which means if you use them in your code running in browsers or alike, you will have to install compatible modules from npm and include them yourself. Here is a list of polyfills webpack has used before webpack 5: ```js -module.exports = { +export default { //... resolve: { fallback: { - assert: require.resolve('assert'), - buffer: require.resolve('buffer'), - console: require.resolve('console-browserify'), - constants: require.resolve('constants-browserify'), - crypto: require.resolve('crypto-browserify'), - domain: require.resolve('domain-browser'), - events: require.resolve('events'), - http: require.resolve('stream-http'), - https: require.resolve('https-browserify'), - os: require.resolve('os-browserify/browser'), - path: require.resolve('path-browserify'), - punycode: require.resolve('punycode'), - process: require.resolve('process/browser'), - querystring: require.resolve('querystring-es3'), - stream: require.resolve('stream-browserify'), - string_decoder: require.resolve('string_decoder'), - sys: require.resolve('util'), - timers: require.resolve('timers-browserify'), - tty: require.resolve('tty-browserify'), - url: require.resolve('url'), - util: require.resolve('util'), - vm: require.resolve('vm-browserify'), - zlib: require.resolve('browserify-zlib'), + assert: 'assert', + buffer: 'buffer', + console: 'console-browserify', + constants: 'constants-browserify', + crypto: 'crypto-browserify', + domain: 'domain-browser', + events: 'events', + http: 'stream-http', + https: 'https-browserify', + os: 'os-browserify/browser', + path: 'path-browserify', + punycode: 'punycode', + process: 'process/browser', + querystring: 'querystring-es3', + stream: 'stream-browserify', + string_decoder: 'string_decoder', + sys: 'util', + timers: 'timers-browserify', + tty: 'tty-browserify', + url: 'url', + util: 'util', + vm: 'vm-browserify', + zlib: 'browserify-zlib', }, }, }; @@ -521,7 +522,7 @@ When set to true, this option treats user-specified requests as fully specified. **webpack.config.js** ```js -module.exports = { +export default { //... resolve: { fullySpecified: true, @@ -538,7 +539,7 @@ Fields from `package.json` which are used to provide the internal requests of a **webpack.config.js** ```js -module.exports = { +export default { //... resolve: { importsFields: ['browser', 'module', 'main'], @@ -557,7 +558,7 @@ When the `target` property is set to `webworker`, `web`, or left unspecified: **webpack.config.js** ```js -module.exports = { +export default { //... resolve: { mainFields: ['browser', 'module', 'main'], @@ -570,7 +571,7 @@ For any other target (including `node`): **webpack.config.js** ```js -module.exports = { +export default { //... resolve: { mainFields: ['module', 'main'], @@ -598,7 +599,7 @@ The filename to be used while resolving directories. **webpack.config.js** ```js -module.exports = { +export default { //... resolve: { mainFiles: ['index'], @@ -621,7 +622,7 @@ With an absolute path, it will only search in the given directory. **webpack.config.js** ```js -module.exports = { +export default { //... resolve: { modules: ['node_modules'], @@ -634,9 +635,9 @@ If you want to add a directory to search in that takes precedence over `node_mod **webpack.config.js** ```js -const path = require('path'); +import path from 'path'; -module.exports = { +export default { //... resolve: { modules: [path.resolve(__dirname, 'src'), 'node_modules'], @@ -653,7 +654,7 @@ A list of additional resolve plugins which should be applied. It allows plugins **webpack.config.js** ```js -module.exports = { +export default { //... resolve: { plugins: [new DirectoryNamedWebpackPlugin()], @@ -672,7 +673,7 @@ Prefer absolute paths to [`resolve.roots`](#resolveroots) when resolving. **webpack.config.js** ```js -module.exports = { +export default { //... resolve: { preferAbsolute: true, @@ -689,7 +690,7 @@ When enabled, webpack would prefer to resolve module requests as relative reques **webpack.config.js** ```js -module.exports = { +export default { //... resolve: { preferRelative: true, @@ -718,7 +719,7 @@ A list of resolve restrictions to restrict the paths that a request can be resol **webpack.config.js** ```js -module.exports = { +export default { //... resolve: { restrictions: [/\.(sass|scss|css)$/], @@ -736,7 +737,7 @@ A list of directories where requests of server-relative URLs (starting with '/') ```js const fixtures = path.resolve(__dirname, 'fixtures'); -module.exports = { +export default { //... resolve: { roots: [__dirname, fixtures], @@ -755,7 +756,7 @@ When enabled, symlinked resources are resolved to their _real_ path, not their s **webpack.config.js** ```js -module.exports = { +export default { //... resolve: { symlinks: true, @@ -772,7 +773,7 @@ Enable aggressive, but **unsafe**, caching of modules. Passing `true` will cache **webpack.config.js** ```js -module.exports = { +export default { //... resolve: { unsafeCache: true, @@ -787,6 +788,7 @@ For example, you can supply a [Proxy object](https://developer.mozilla.org/en-US **webpack.config.js** ```js +import fs from 'fs'; // copied from discussion here https://github.com/webpack/webpack/discussions/18089 const realUnsafeCache = {}; const unsafeCacheHandler = { @@ -804,7 +806,7 @@ const unsafeCacheHandler = { }, }; const theProxiedCache = new Proxy(realUnsafeCache, unsafeCacheHandler); -module.exports = { +export default { //... resolve: { unsafeCache: theProxiedCache, @@ -823,7 +825,7 @@ Use synchronous filesystem calls for the resolver. **webpack.config.js** ```js -module.exports = { +export default { //... resolve: { useSyncFileSystemCalls: true, @@ -840,7 +842,7 @@ This set of options is identical to the `resolve` property set above, but is use **webpack.config.js** ```js -module.exports = { +export default { //... resolveLoader: { modules: ['node_modules'], diff --git a/src/content/configuration/stats.mdx b/src/content/configuration/stats.mdx index 75d9e9e40015..a931f1585410 100644 --- a/src/content/configuration/stats.mdx +++ b/src/content/configuration/stats.mdx @@ -26,7 +26,7 @@ The `stats` option lets you precisely control what bundle information gets displ W> This option does not have any effect when using the [Node.js API](/api/node). You need to pass the stats options to the `stats.toString()` resp. `stats.toJson()` calls instead. ```js -module.exports = { +export default { //... stats: 'errors-only', }; @@ -58,7 +58,7 @@ T> All of the options in the stats configuration object are optional. A fallback value for stats options when an option is not defined. It has precedence over local webpack defaults. ```javascript -module.exports = { +export default { //... stats: { all: undefined, @@ -73,7 +73,7 @@ module.exports = { Tells `stats` whether to show the asset information. Set `stats.assets` to `false` to hide it. ```javascript -module.exports = { +export default { //... stats: { assets: false, @@ -88,7 +88,7 @@ module.exports = { Tells `stats` to sort the assets by a given field. All of the [sorting fields](#sorting-fields) are allowed to be used as values for `stats.assetsSort`. Use `!` prefix in the value to reverse the sort order by a given field. ```javascript -module.exports = { +export default { //... stats: { assetsSort: '!size', @@ -103,7 +103,7 @@ module.exports = { Tells `stats` how many items of assets should be displayed (groups will be collapsed to fit this space). ```javascript -module.exports = { +export default { //... stats: { assetsSpace: 15, @@ -118,7 +118,7 @@ module.exports = { Tells `stats` whether to add the build date and the build time information. Set `stats.builtAt` to `false` to hide it. ```javascript -module.exports = { +export default { //... stats: { builtAt: false, @@ -137,7 +137,7 @@ Old version of `stats.cachedModules`. Tells `stats` whether to add information about the cached assets. Setting `stats.cachedAssets` to `false` will tell `stats` to only show the emitted files (not the ones that were built). ```javascript -module.exports = { +export default { //... stats: { cachedAssets: false, @@ -152,7 +152,7 @@ module.exports = { Tells `stats` whether to add information about cached (not built) modules. ```javascript -module.exports = { +export default { //... stats: { cachedModules: false, @@ -167,7 +167,7 @@ module.exports = { Tells `stats` whether to add information about the children. ```javascript -module.exports = { +export default { //... stats: { children: false, @@ -182,7 +182,7 @@ module.exports = { Display auxiliary assets in chunk groups. ```javascript -module.exports = { +export default { //... stats: { chunkGroupAuxiliary: false, @@ -197,7 +197,7 @@ module.exports = { Display children of the chunk groups (e.g. prefetched, preloaded chunks and assets). ```javascript -module.exports = { +export default { //... stats: { chunkGroupChildren: false, @@ -212,7 +212,7 @@ module.exports = { Limit of assets displayed in chunk groups. ```javascript -module.exports = { +export default { //... stats: { chunkGroupMaxAssets: 5, @@ -227,7 +227,7 @@ module.exports = { Tells `stats` whether to add information about the `namedChunkGroups`. ```javascript -module.exports = { +export default { //... stats: { chunkGroups: false, @@ -242,7 +242,7 @@ module.exports = { Tells `stats` whether to add information about the built modules to information about the chunk. ```javascript -module.exports = { +export default { //... stats: { chunkModules: false, @@ -257,7 +257,7 @@ module.exports = { Tells `stats` how many items of chunk modules should be displayed (groups will be collapsed to fit this space). ```javascript -module.exports = { +export default { //... stats: { chunkModulesSpace: 15, @@ -272,7 +272,7 @@ module.exports = { Tells `stats` whether to add information about the origins of chunks and chunk merging. ```javascript -module.exports = { +export default { //... stats: { chunkOrigins: false, @@ -287,7 +287,7 @@ module.exports = { Tells `stats` to display chunk parents, children and siblings. ```javascript -module.exports = { +export default { //... stats: { chunkRelations: false, @@ -302,7 +302,7 @@ module.exports = { Tells `stats` whether to add information about the chunk. Setting `stats.chunks` to `false` results in a less verbose output. ```javascript -module.exports = { +export default { //... stats: { chunks: false, @@ -317,7 +317,7 @@ module.exports = { Tells `stats` to sort the chunks by a given field. All of the [sorting fields](#sorting-fields) are allowed to be used as values for `stats.chunksSort`. Use `!` prefix in the value to reverse the sort order by a given field. ```javascript -module.exports = { +export default { //... stats: { chunksSort: 'name', @@ -332,7 +332,7 @@ module.exports = { Tells `stats` whether to output in the different colors. ```javascript -module.exports = { +export default { //... stats: { colors: true, @@ -355,7 +355,7 @@ npx webpack --no-stats-colors You can specify your own terminal output colors using [ANSI escape sequences](https://en.wikipedia.org/wiki/ANSI_escape_code) ```js -module.exports = { +export default { //... colors: { green: '\u001b[32m', @@ -370,9 +370,9 @@ module.exports = { The stats base directory, an **absolute path** for shortening the request information. ```javascript -const path = require('path'); +import path from 'path'; -module.exports = { +export default { //... stats: { context: path.resolve(__dirname, 'src/components'), @@ -389,7 +389,7 @@ By default, the value of [`context`](/configuration/entry-context/#context) or t Tells `stats` whether to show chunk modules that are dependencies of other modules of the chunk. ```javascript -module.exports = { +export default { //... stats: { dependentModules: false, @@ -404,7 +404,7 @@ module.exports = { Tells `stats` whether to display the distance from the entry point for each module. ```javascript -module.exports = { +export default { //... stats: { depth: true, @@ -419,7 +419,7 @@ module.exports = { Tells `stats` whether to display the entry points with the corresponding bundles. ```javascript -module.exports = { +export default { //... stats: { entrypoints: false, @@ -436,7 +436,7 @@ When `stats.entrypoints` is set to `'auto'`, webpack will decide automatically w Tells `stats` whether to display the `--env` information. ```javascript -module.exports = { +export default { //... stats: { env: true, @@ -451,7 +451,7 @@ module.exports = { Tells `stats` whether to include the [`cause`](https://nodejs.org/en/blog/release/v16.9.0/#error-cause) property of errors in the output. It defaults to `true`. ```javascript -module.exports = { +export default { //... stats: { errorCause: true, @@ -466,7 +466,7 @@ module.exports = { Tells `stats` whether to add the details to the errors. It defaults to `'auto'` which will show error details when there're only 2 or less errors. ```javascript -module.exports = { +export default { //... stats: { errorDetails: false, @@ -483,7 +483,7 @@ Tells `stats` whether to include the errors array from [`AggregateError`](https: Useful when a single error is composed of multiple underlying errors, providing deeper visibility into grouped error structures. ```javascript -module.exports = { +export default { //... stats: { errorErrors: true, @@ -498,7 +498,7 @@ module.exports = { Tells `stats` whether to show stack trace of errors. ```javascript -module.exports = { +export default { //... stats: { errorStack: false, @@ -513,7 +513,7 @@ module.exports = { Tells `stats` whether to display the errors. ```javascript -module.exports = { +export default { //... stats: { errors: false, @@ -528,7 +528,7 @@ module.exports = { Add errors count. ```javascript -module.exports = { +export default { //... stats: { errorsCount: false, @@ -545,7 +545,7 @@ module.exports = { Tells `stats` to limit the number of lines to allocate for displaying an error. ```javascript -module.exports = { +export default { //... stats: { errorsSpace: 5, @@ -564,7 +564,7 @@ See [`stats.excludeModules`](#statsexcludemodules). Tells `stats` to exclude the matching assets information. This can be done with a `string`, a `RegExp`, a `function` that is getting the assets name as an argument and returns a `boolean`. `stats.excludeAssets` can be an `array` of any of the above. ```javascript -module.exports = { +export default { //... stats: { excludeAssets: [ @@ -583,7 +583,7 @@ module.exports = { Tells `stats` to exclude the matching modules information. This can be done with a `string`, a `RegExp`, a `function` that is getting the module's source as an argument and returns a `boolean`. `stats.excludeModules` can be an `array` of any of the above. `stats.excludeModules`'s configuration [is merged](https://github.com/webpack/webpack/blob/main/lib/Stats.js#L215) with the `stats.exclude`'s configuration value. ```javascript -module.exports = { +export default { //... stats: { excludeModules: ['filter', /filter/, (moduleSource) => true], @@ -594,7 +594,7 @@ module.exports = { Setting `stats.excludeModules` to `false` will disable the exclude behaviour. ```javascript -module.exports = { +export default { //... stats: { excludeModules: false, @@ -609,7 +609,7 @@ module.exports = { Tells `stats` whether to group assets by how their are related to chunks. ```javascript -module.exports = { +export default { //... stats: { groupAssetsByChunk: false, @@ -624,7 +624,7 @@ module.exports = { Tells `stats` whether to group assets by their status (emitted, compared for emit or cached). ```javascript -module.exports = { +export default { //... stats: { groupAssetsByEmitStatus: false, @@ -639,7 +639,7 @@ module.exports = { Tells `stats` whether to group assets by their extension. ```javascript -module.exports = { +export default { //... stats: { groupAssetsByExtension: false, @@ -654,7 +654,7 @@ module.exports = { Tells `stats` whether to group assets by their asset info (immutable, development, hotModuleReplacement, etc). ```javascript -module.exports = { +export default { //... stats: { groupAssetsByInfo: false, @@ -669,7 +669,7 @@ module.exports = { Tells `stats` whether to group assets by their asset path. ```javascript -module.exports = { +export default { //... stats: { groupAssetsByPath: false, @@ -684,7 +684,7 @@ module.exports = { Tells `stats` whether to group modules by their attributes (errors, warnings, assets, optional, orphan, or dependent). ```javascript -module.exports = { +export default { //... stats: { groupModulesByAttributes: false, @@ -699,7 +699,7 @@ module.exports = { Tells `stats` whether to group modules by their cache status (cached or built and cacheable). ```javascript -module.exports = { +export default { //... stats: { groupModulesByCacheStatus: true, @@ -714,7 +714,7 @@ module.exports = { Tells `stats` whether to group modules by their extension. ```javascript -module.exports = { +export default { //... stats: { groupModulesByExtension: true, @@ -729,7 +729,7 @@ module.exports = { Tells `stats` whether to group modules by their layer. ```javascript -module.exports = { +export default { //... stats: { groupModulesByLayer: true, @@ -744,7 +744,7 @@ module.exports = { Tells `stats` whether to group modules by their path. ```javascript -module.exports = { +export default { //... stats: { groupModulesByPath: true, @@ -759,7 +759,7 @@ module.exports = { Tells `stats` whether to group modules by their type. ```javascript -module.exports = { +export default { //... stats: { groupModulesByType: true, @@ -776,7 +776,7 @@ module.exports = { Group [`reasons`](#statsreasons) by their origin module to avoid large set of reasons. ```javascript -module.exports = { +export default { //... stats: { groupReasonsByOrigin: true, @@ -791,7 +791,7 @@ module.exports = { Tells `stats` whether to add information about the hash of the compilation. ```javascript -module.exports = { +export default { //... stats: { hash: false, @@ -806,7 +806,7 @@ module.exports = { Tells `stats` to add IDs of modules and chunks. ```javascript -module.exports = { +export default { //... stats: { ids: true, @@ -828,7 +828,7 @@ Tells `stats` whether to add logging output. - `'verbose'` - log everything except debug and trace. Collapsed groups are displayed in expanded state. ```javascript -module.exports = { +export default { //... stats: { logging: 'verbose', @@ -843,7 +843,7 @@ module.exports = { Tells `stats` to include the debug information of the specified loggers such as Plugins or Loaders. When [`stats.logging`](#statslogging) is set to `false`, `stats.loggingDebug` option is ignored. ```javascript -module.exports = { +export default { //... stats: { loggingDebug: [ @@ -863,7 +863,7 @@ module.exports = { Enable stack traces in the logging output for errors, warnings and traces. Set `stats.loggingTrace` to hide the trace. ```javascript -module.exports = { +export default { //... stats: { loggingTrace: false, @@ -878,7 +878,7 @@ module.exports = { Tells `stats` whether to add information about assets inside modules. Set `stats.moduleAssets` to `false` to hide it. ```javascript -module.exports = { +export default { //... stats: { moduleAssets: false, @@ -893,7 +893,7 @@ module.exports = { Tells `stats` to show dependencies and the origin of warnings/errors. `stats.moduleTrace` is available since webpack 2.5.0. ```javascript -module.exports = { +export default { //... stats: { moduleTrace: false, @@ -908,7 +908,7 @@ module.exports = { Tells `stats` whether to add information about the built modules. ```javascript -module.exports = { +export default { //... stats: { modules: false, @@ -923,7 +923,7 @@ module.exports = { Tells `stats` to sort the modules by a given field. All of the [sorting fields](#sorting-fields) are allowed to be used as values for `stats.modulesSort`. Use `!` prefix in the value to reverse the sort order by a given field. ```javascript -module.exports = { +export default { //... stats: { modulesSort: 'size', @@ -938,7 +938,7 @@ module.exports = { Tells `stats` how many items of modules should be displayed (groups will be collapsed to fit this space). ```javascript -module.exports = { +export default { //... stats: { modulesSpace: 15, @@ -953,7 +953,7 @@ module.exports = { Tells `stats` whether to add information about modules nested in other modules (like with module concatenation). ```javascript -module.exports = { +export default { //... stats: { nestedModules: true, @@ -968,7 +968,7 @@ module.exports = { Tells `stats` how many items of nested modules should be displayed (groups will be collapsed to fit this space). ```javascript -module.exports = { +export default { //... stats: { nestedModulesSpace: 15, @@ -983,7 +983,7 @@ module.exports = { Tells `stats` to show the reasons why optimization bailed out for modules. ```javascript -module.exports = { +export default { //... stats: { optimizationBailout: false, @@ -998,7 +998,7 @@ module.exports = { Tells `stats` whether to hide `orphan` modules. A module is an `orphan` if it is not included in any chunk. Orphan modules are hidden by default in `stats`. ```javascript -module.exports = { +export default { //... stats: { orphanModules: true, @@ -1013,7 +1013,7 @@ module.exports = { Tells `stats` to show the `outputPath`. ```javascript -module.exports = { +export default { //... stats: { outputPath: false, @@ -1028,7 +1028,7 @@ module.exports = { Tells `stats` to show performance hint when the file size exceeds [`performance.maxAssetSize`](/configuration/performance/#performancemaxassetsize). ```javascript -module.exports = { +export default { //... stats: { performance: false, @@ -1043,7 +1043,7 @@ module.exports = { Sets the [preset](/configuration/stats/#stats-presets) for the type of information that gets displayed. It is useful for [extending stats behaviours](/configuration/stats/#extending-stats-behaviours). ```javascript -module.exports = { +export default { //... stats: { preset: 'minimal', @@ -1060,7 +1060,7 @@ Setting value of `stats.preset` to `false` tells webpack to use `'none'` [stats Tells `stats` to show the exports of the modules. ```javascript -module.exports = { +export default { //... stats: { providedExports: true, @@ -1075,7 +1075,7 @@ module.exports = { Tells `stats` to show the `publicPath`. ```javascript -module.exports = { +export default { //... stats: { publicPath: false, @@ -1090,7 +1090,7 @@ module.exports = { Tells `stats` to add information about the reasons of why modules are included. ```javascript -module.exports = { +export default { //... stats: { reasons: false, @@ -1107,7 +1107,7 @@ module.exports = { Space to display [`reasons`](#statsreasons) (groups will be collapsed to fit this space). ```javascript -module.exports = { +export default { //... stats: { reasonsSpace: 1000, @@ -1124,7 +1124,7 @@ T> The [`detailed preset`](#stats-presets) limits [`modulesSpace`](#statsmodules Tells `stats` whether to add information about assets that are related to other assets (like SourceMaps for assets). ```javascript -module.exports = { +export default { //... stats: { relatedAssets: true, @@ -1139,7 +1139,7 @@ module.exports = { Tells `stats` whether to add information about runtime modules. ```javascript -module.exports = { +export default { //... stats: { runtimeModules: false, @@ -1154,7 +1154,7 @@ module.exports = { Tells `stats` to add the source code of modules. ```javascript -module.exports = { +export default { //... stats: { source: true, @@ -1169,7 +1169,7 @@ module.exports = { Tells `stats` to add the timing information. ```javascript -module.exports = { +export default { //... stats: { timings: false, @@ -1184,7 +1184,7 @@ module.exports = { Tells `stats` whether to show which exports of a module are used. ```javascript -module.exports = { +export default { //... stats: { usedExports: true, @@ -1199,7 +1199,7 @@ module.exports = { Tells `stats` to add information about the webpack version used. ```javascript -module.exports = { +export default { //... stats: { version: false, @@ -1214,7 +1214,7 @@ module.exports = { Tells `stats` to add warnings. ```javascript -module.exports = { +export default { //... stats: { warnings: false, @@ -1229,7 +1229,7 @@ module.exports = { Add warnings count. ```javascript -module.exports = { +export default { //... stats: { warningsCount: false, @@ -1244,7 +1244,7 @@ module.exports = { Tells `stats` to exclude the warnings that are matching given filters. This can be done with a `string`, a `RegExp`, a `function` that is getting a warning as an argument and returns a `boolean`. `stats.warningsFilter` can be an `array` of any of the above. ```javascript -module.exports = { +export default { //... stats: { warningsFilter: ['filter', /filter/, (warning) => true], @@ -1263,7 +1263,7 @@ W> `stats.warningsFilter` is deprecated in favor of [`ignoreWarnings`](/configur Tells `stats` to limit the number of lines to allocate for displaying a warning. ```javascript -module.exports = { +export default { //... stats: { warningsSpace: 5, @@ -1302,7 +1302,7 @@ If you want to use one of the presets e.g. `'minimal'` but still override some o **webpack.config.js** ```javascript -module.exports = { +export default { //.. stats: { preset: 'minimal', diff --git a/src/content/configuration/target.mdx b/src/content/configuration/target.mdx index 1ee614ffa4e7..b8371832f3ca 100644 --- a/src/content/configuration/target.mdx +++ b/src/content/configuration/target.mdx @@ -50,7 +50,7 @@ A version of `node` or `electron` may be optionally specified. This is denoted b **webpack.config.js** ```js -module.exports = { +export default { // ... target: 'node12.18', }; @@ -80,7 +80,7 @@ When multiple targets are passed, then common subset of features will be used: **webpack.config.js** ```js -module.exports = { +export default { // ... target: ['web', 'es5'], }; @@ -93,7 +93,7 @@ Not all targets may be mixed for now. **webpack.config.js** ```js -module.exports = { +export default { // ... target: ['web', 'node'], }; @@ -108,7 +108,7 @@ Set `target` to `false` if none of the predefined targets from the list above me **webpack.config.js** ```js -module.exports = { +export default { // ... target: false, }; @@ -119,9 +119,9 @@ Or you can apply specific plugins you want: **webpack.config.js** ```js -const webpack = require('webpack'); +import webpack from 'webpack'; -module.exports = { +export default { // ... target: false, plugins: [ diff --git a/src/content/configuration/watch.mdx b/src/content/configuration/watch.mdx index bdcc652ec7a4..99ed563576d8 100644 --- a/src/content/configuration/watch.mdx +++ b/src/content/configuration/watch.mdx @@ -25,7 +25,7 @@ Turn on watch mode. This means that after the initial build, webpack will contin **webpack.config.js** ```javascript -module.exports = { +export default { //... watch: true, }; @@ -42,7 +42,7 @@ A set of options used to customize watch mode: **webpack.config.js** ```javascript -module.exports = { +export default { //... watchOptions: { aggregateTimeout: 200, @@ -58,7 +58,7 @@ module.exports = { Add a delay before rebuilding once the first file changed. This allows webpack to aggregate any other changes made during this time period into one rebuild. Pass a value in milliseconds: ```javascript -module.exports = { +export default { //... watchOptions: { aggregateTimeout: 600, @@ -75,7 +75,7 @@ For some systems, watching many files can result in a lot of CPU or memory usage **webpack.config.js** ```javascript -module.exports = { +export default { //... watchOptions: { ignored: /node_modules/, @@ -88,7 +88,7 @@ Alternatively, a glob pattern may be used: **webpack.config.js** ```javascript -module.exports = { +export default { //... watchOptions: { ignored: '**/node_modules', @@ -101,7 +101,7 @@ It is also possible to use multiple glob patterns: **webpack.config.js** ```javascript -module.exports = { +export default { //... watchOptions: { ignored: ['**/files/**/*.js', '**/node_modules'], @@ -112,8 +112,8 @@ module.exports = { In addition, you can specify an absolute path: ```js -const path = require('path'); -module.exports = { +import path from 'path'; +export default { //... watchOptions: { ignored: [path.posix.resolve(__dirname, './ignored-dir')], @@ -123,7 +123,7 @@ module.exports = { When using glob patterns, we convert them to regular expressions with [`glob-to-regexp`](https://github.com/fitzgen/glob-to-regexp), so make sure to get yourself familiar with it before you use glob patterns for `watchOptions.ignored`. -T> If you use `require.context`, webpack will watch your entire directory. You will need to ignore files and/or directories so that unwanted changes will not trigger a rebuild. +T> If you use `import.meta.webpackContext`, webpack will watch your entire directory. You will need to ignore files and/or directories so that unwanted changes will not trigger a rebuild. ### watchOptions.poll @@ -134,7 +134,7 @@ Turn on [polling]() by **webpack.config.js** ```javascript -module.exports = { +export default { //... watchOptions: { poll: 1000, // Check for changes every second @@ -152,7 +152,7 @@ Follow symbolic links while looking for a file. This is usually not needed as we - Example: ```js - module.exports = { + export default { //... watchOptions: { followSymlinks: true, @@ -168,7 +168,7 @@ Stop watching when stdin stream has ended. - Example: ```js - module.exports = { + export default { //... watchOptions: { stdin: true, @@ -206,7 +206,7 @@ On macOS, folders can get corrupted in certain scenarios. See [this article](htt Because webpack expects absolute paths for many configuration options such as `__dirname + '/app/folder'` the Windows `\` path separator can break some functionality. -Use the correct separators. I.e. `path.resolve(__dirname, 'app/folder')` or `path.join(__dirname, 'app', 'folder')`. +Use the correct separators. We recommend using $\text{Node.js}$'s built-in path module utilities like $\text{path.resolve}$ or $\text{path.join}$ (often paired with $\text{import.meta.url}$ in ESM projects) to handle absolute paths correctly across operating systems. ### Vim diff --git a/src/content/contribute/plugin-patterns.mdx b/src/content/contribute/plugin-patterns.mdx index 930772f392c3..1e135c831ad8 100644 --- a/src/content/contribute/plugin-patterns.mdx +++ b/src/content/contribute/plugin-patterns.mdx @@ -32,7 +32,7 @@ class MyPlugin { // Explore each asset filename generated by the chunk: chunk.files.forEach((filename) => { // Get the asset source for each file generated by the chunk: - var source = compilation.assets[filename].source(); + const source = compilation.assets[filename].source(); }); }); @@ -40,14 +40,14 @@ class MyPlugin { }); } } -module.exports = MyPlugin; +export default MyPlugin; ``` - `compilation.modules`: A set of modules (built inputs) in the compilation. Each module manages the build of a raw file from your source library. W> **Deprecation warning**: Array functions will still work. -- `module.fileDependencies`: An array of source file paths included into a module. This includes the source JavaScript file itself (ex: `index.js`), and all dependency asset files (stylesheets, images, etc) that it has required. Reviewing dependencies is useful for seeing what source files belong to a module. +- `module.fileDependencies`: An array of source file paths included into a module. This includes the source JavaScript file itself (ex: `index.js`), and all dependency asset files (stylesheets, images, etc) that it has imported. Reviewing dependencies is useful for seeing what source files belong to a module. - `compilation.chunks`: A set of chunks (build outputs) in the compilation. Each chunk manages the composition of a final rendered assets. W> **Deprecation warning**: Array functions will still work. @@ -82,7 +82,7 @@ class MyPlugin { } } -module.exports = MyPlugin; +export default MyPlugin; ``` You may also feed new file paths into the watch graph to receive compilation triggers when those files change. Add valid file paths into the `compilation.fileDependencies` `Set` to add them to the watched files. @@ -102,8 +102,8 @@ class MyPlugin { } apply(compiler) { compiler.hooks.emit.tapAsync('MyPlugin', (compilation, callback) => { - var changedChunks = compilation.chunks.filter((chunk) => { - var oldVersion = this.chunkVersions[chunk.name]; + const changedChunks = compilation.chunks.filter((chunk) => { + const oldVersion = this.chunkVersions[chunk.name]; this.chunkVersions[chunk.name] = chunk.hash; return chunk.hash !== oldVersion; }); @@ -112,5 +112,5 @@ class MyPlugin { } } -module.exports = MyPlugin; +export default MyPlugin; ``` diff --git a/src/content/contribute/writing-a-loader.mdx b/src/content/contribute/writing-a-loader.mdx index e7286112a96e..61fedfbca793 100644 --- a/src/content/contribute/writing-a-loader.mdx +++ b/src/content/contribute/writing-a-loader.mdx @@ -23,9 +23,9 @@ To test a single loader, you can use `path` to `resolve` a local file within a r **webpack.config.js** ```js -const path = require('path'); +import path from 'path'; -module.exports = { +export default { //... module: { rules: [ @@ -50,9 +50,9 @@ To test multiple, you can utilize the `resolveLoader.modules` configuration to u **webpack.config.js** ```js -const path = require('path'); +import path from 'path'; -module.exports = { +export default { //... resolveLoader: { modules: ['node_modules', path.resolve(__dirname, 'loaders')], @@ -85,7 +85,7 @@ In the following example, the `foo-loader` would be passed the raw resource and **webpack.config.js** ```js -module.exports = { +export default { //... module: { rules: [ @@ -216,7 +216,7 @@ Depending on the type of module, there may be a different schema used to specify This can be done in one of two ways: -- By transforming them to `require` statements. +- By transforming them to `import` or require` statements. - Using the `this.resolve` function to resolve the path. The `css-loader` is a good example of the first approach. It transforms dependencies to `require`s, by replacing `@import` statements with a `require` to the other stylesheet and `url(...)` with a `require` to the referenced file. @@ -232,13 +232,13 @@ Avoid generating common code in every module the loader processes. Instead, crea **src/loader-runtime.js** ```js -const { someOtherModule } = require('./some-other-module'); +import { someOtherModule } from './some-other-module.js'; -module.exports = function runtime(params) { +export default function runtime(params) { const x = params.y * 2; return someOtherModule(params, x); -}; +} ``` **src/loader.js** @@ -263,10 +263,7 @@ Don't insert absolute paths into the module code as they break hashing when the ```js // `loaderContext` is same as `this` inside loader function JSON.stringify( - loaderContext.utils.contextify( - loaderContext.context || loaderContext.rootContext, - request - ) + this.utils.contextify(this.context || this.rootContext, request) ); ``` @@ -295,7 +292,7 @@ npm install --save-dev jest babel-jest @babel/core @babel/preset-env **babel.config.js** ```js -module.exports = { +export default { presets: [ [ '@babel/preset-env', diff --git a/src/content/contribute/writing-a-plugin.mdx b/src/content/contribute/writing-a-plugin.mdx index 0e909f6ad350..555a6955db0d 100644 --- a/src/content/contribute/writing-a-plugin.mdx +++ b/src/content/contribute/writing-a-plugin.mdx @@ -69,16 +69,16 @@ class HelloWorldPlugin { } } -module.exports = HelloWorldPlugin; +export default HelloWorldPlugin; ``` Then to use the plugin, include an instance in your webpack configuration `plugins` array: ```javascript // webpack.config.js -var HelloWorldPlugin = require('hello-world'); +import HelloWorldPlugin from 'hello-world'; -module.exports = { +export default { // ... configuration settings here ... plugins: [new HelloWorldPlugin({ options: true })], }; @@ -128,7 +128,7 @@ class HelloCompilationPlugin { } } -module.exports = HelloCompilationPlugin; +export default HelloCompilationPlugin; ``` For the list of hooks available on `compiler`, `compilation`, and other important objects, see the [plugins API](/api/plugins/) docs. @@ -157,7 +157,7 @@ class HelloAsyncPlugin { } } -module.exports = HelloAsyncPlugin; +export default HelloAsyncPlugin; ``` #### tapPromise @@ -179,7 +179,7 @@ class HelloAsyncPlugin { } } -module.exports = HelloAsyncPlugin; +export default HelloAsyncPlugin; ``` ## Example @@ -255,16 +255,16 @@ class FileListPlugin { } } -module.exports = { FileListPlugin }; +export { FileListPlugin }; ``` **webpack.config.js** ```javascript -const { FileListPlugin } = require('./file-list-plugin.js'); +import { FileListPlugin } from './file-list-plugin.js'; // Use the plugin in your webpack configuration: -module.exports = { +export default { // … plugins: [ @@ -314,13 +314,11 @@ Various types of hooks supported are : ### Synchronous Hooks - **SyncHook** - - Defined as `new SyncHook([params])` - Tapped into using `tap` method. - Called using `call(...params)` method. - **Bail Hooks** - - Defined using `SyncBailHook[params]` - Tapped into using `tap` method. - Called using `call(...params)` method. @@ -328,7 +326,6 @@ Various types of hooks supported are : In these types of hooks, each of the plugin callbacks will be invoked one after the other with the specific `args`. If any value is returned except undefined by any plugin, then that value is returned by hook and no further plugin callback is invoked. Many useful events like `optimizeChunks`, `optimizeChunkModules` are SyncBailHooks. - **Waterfall Hooks** - - Defined using `SyncWaterfallHook[params]` - Tapped into using `tap` method. - Called using `call(...params)` method @@ -339,7 +336,6 @@ Various types of hooks supported are : ### Asynchronous Hooks - **Async Series Hook** - - Defined using `AsyncSeriesHook[params]` - Tapped into using `tap`/`tapAsync`/`tapPromise` method. - Called using `callAsync(...params)` method @@ -348,7 +344,6 @@ Various types of hooks supported are : This is also a commonly used pattern for events like `emit`, `run`. - **Async waterfall** The plugins will be applied asynchronously in the waterfall manner. - - Defined using `AsyncWaterfallHook[params]` - Tapped into using `tap`/`tapAsync`/`tapPromise` method. - Called using `callAsync(...params)` method @@ -357,13 +352,11 @@ Various types of hooks supported are : This plugin pattern is expected for events like `before-resolve` and `after-resolve`. - **Async Series Bail** - - Defined using `AsyncSeriesBailHook[params]` - Tapped into using `tap`/`tapAsync`/`tapPromise` method. - Called using `callAsync(...params)` method - **Async Parallel** - - Defined using `AsyncParallelHook[params]` - Tapped into using `tap`/`tapAsync`/`tapPromise` method. - Called using `callAsync(...params)` method diff --git a/src/content/guides/asset-management.mdx b/src/content/guides/asset-management.mdx index 2ea4ae4bd8fa..2e10bbdb6a11 100644 --- a/src/content/guides/asset-management.mdx +++ b/src/content/guides/asset-management.mdx @@ -44,9 +44,9 @@ Let's make a minor change to our project before we get started: **webpack.config.js** ```diff - const path = require('path'); + import path from 'path'; - module.exports = { + export default { entry: './src/index.js', output: { - filename: 'main.js', @@ -67,9 +67,9 @@ npm install --save-dev style-loader css-loader **webpack.config.js** ```diff - const path = require('path'); + import path from 'path'; - module.exports = { + export default { entry: './src/index.js', output: { filename: 'bundle.js', @@ -171,9 +171,9 @@ So now we're pulling in our CSS, but what about our images like backgrounds and **webpack.config.js** ```diff - const path = require('path'); + import path from 'path'; - module.exports = { + export default { entry: './src/index.js', output: { filename: 'bundle.js', @@ -284,9 +284,9 @@ So what about other assets like fonts? The Asset Modules will take any file you **webpack.config.js** ```diff - const path = require('path'); + import path from 'path'; - module.exports = { + export default { entry: './src/index.js', output: { filename: 'bundle.js', @@ -395,9 +395,9 @@ npm install --save-dev csv-loader xml-loader **webpack.config.js** ```diff - const path = require('path'); + import path from 'path'; - module.exports = { + export default { entry: './src/index.js', output: { filename: 'bundle.js', @@ -579,12 +579,12 @@ And configure them in your webpack configuration: **webpack.config.js** ```diff - const path = require('path'); -+const toml = require('toml'); -+const yaml = require('yamljs'); -+const json5 = require('json5'); + import path from 'path'; ++import toml from 'toml'; ++import yaml from 'yamljs'; ++import json5 from 'json5'; - module.exports = { + export default { entry: './src/index.js', output: { filename: 'bundle.js', @@ -732,12 +732,12 @@ For the next guides we won't be using all the different assets we've used in thi **webpack.config.js** ```diff - const path = require('path'); --const toml = require('toml'); --const yaml = require('yamljs'); --const json5 = require('json5'); + import path from 'path'; +-import toml from 'toml'; +-import yaml from 'yamljs'; +-import json5 from 'json5'; - module.exports = { + export default { entry: './src/index.js', output: { filename: 'bundle.js', diff --git a/src/content/guides/asset-modules.mdx b/src/content/guides/asset-modules.mdx index 6af7c775666f..65d5812c15f0 100644 --- a/src/content/guides/asset-modules.mdx +++ b/src/content/guides/asset-modules.mdx @@ -35,7 +35,7 @@ When using the old assets loaders (i.e. `file-loader`/`url-loader`/`raw-loader`) **webpack.config.js** ```diff -module.exports = { +export default { module: { rules: [ { @@ -60,7 +60,7 @@ To exclude assets that came from new URL calls from the asset loaders add `depen **webpack.config.js** ```diff -module.exports = { +export default { module: { rules: [ { @@ -95,7 +95,7 @@ __webpack_public_path__ = 'https://cdn.url.com'; And then in your `webpack.config.js` updating your `entry` field to look like ```javascript -module.exports = { +export default { entry: ['./publicPath.js', './App.js'], }; ``` @@ -111,9 +111,9 @@ import './publicPath.js'; **webpack.config.js** ```diff -const path = require('path'); +import path from 'path'; -module.exports = { +export default { entry: './src/index.js', output: { filename: 'main.js', @@ -149,9 +149,9 @@ You can modify this template by setting [`output.assetModuleFilename`](/configur **webpack.config.js** ```diff -const path = require('path'); +import path from 'path'; -module.exports = { +export default { entry: './src/index.js', output: { filename: 'main.js', @@ -172,9 +172,9 @@ module.exports = { Another case to customize output filename is to emit some kind of assets to a specified directory: ```diff -const path = require('path'); +import path from 'path'; -module.exports = { +export default { entry: './src/index.js', output: { filename: 'main.js', @@ -204,9 +204,9 @@ With this configuration all the `html` files will be emitted into a `static` dir **webpack.config.js** ```js -const path = require('path'); +import path from 'path'; -module.exports = { +export default { entry: './src/index.js', output: { filename: 'main.js', @@ -242,10 +242,10 @@ If you want to use a custom encoding algorithm, you may specify a custom functio **webpack.config.js** ```diff -const path = require('path'); -+ const svgToMiniDataURI = require('mini-svg-data-uri'); +import path from 'path'; ++ import svgToMiniDataURI from 'mini-svg-data-uri'; -module.exports = { +export default { entry: './src/index.js', output: { filename: 'main.js', @@ -275,9 +275,9 @@ Now all `.svg` files will be encoded by `mini-svg-data-uri` package. **webpack.config.js** ```diff -const path = require('path'); +import path from 'path'; -module.exports = { +export default { entry: './src/index.js', output: { filename: 'main.js', @@ -369,9 +369,9 @@ console.log(url.pathname === ','); **webpack.config.js** ```diff -const path = require('path'); +import path from 'path'; -module.exports = { +export default { entry: './src/index.js', output: { filename: 'main.js', @@ -395,9 +395,9 @@ You can change this condition by setting a [`Rule.parser.dataUrlCondition.maxSiz **webpack.config.js** ```diff -const path = require('path'); +import path from 'path'; -module.exports = { +export default { entry: './src/index.js', output: { filename: 'main.js', @@ -426,9 +426,9 @@ Also you can [specify a function](/configuration/module/#ruleparserdataurlcondit **webpack.config.js** ```diff -const path = require('path'); +import path from 'path'; -module.exports = { +export default { entry: './src/index.js', output: { filename: 'main.js', @@ -550,7 +550,7 @@ module: { For use cases like Server side rendering, you might want to disable emitting assets, which is feasible with [`emit`](/configuration/module/#rulegeneratoremit) option under `Rule.generator`: ```js -module.exports = { +export default { // … module: { rules: [ diff --git a/src/content/guides/author-libraries.mdx b/src/content/guides/author-libraries.mdx index 6003f7db4203..aae69e05f915 100644 --- a/src/content/guides/author-libraries.mdx +++ b/src/content/guides/author-libraries.mdx @@ -106,9 +106,12 @@ Let's start with this basic webpack configuration: **webpack.config.js** ```js -const path = require('path'); +import path from 'path'; +import { fileURLToPath } from 'url'; -module.exports = { +const __dirname = path.dirname(fileURLToPath(import.meta.url)); + +export default { entry: './src/index.js', output: { path: path.resolve(__dirname, 'dist'), @@ -126,9 +129,12 @@ So far everything should be the same as bundling an application, and here comes **webpack.config.js** ```diff - const path = require('path'); + import path from 'path'; + import { fileURLToPath } from 'url'; + + const __dirname = path.dirname(fileURLToPath(import.meta.url)); - module.exports = { + export default { entry: './src/index.js', output: { path: path.resolve(__dirname, 'dist'), @@ -151,6 +157,14 @@ However it only works when it's referenced through script tag, it can't be used As a library author, we want it to be compatible in different environments, i.e., users should be able to consume the bundled library in multiple ways listed below: +- **ES Module import**: + + ```js + import { wordToNum } from 'webpack-numbers'; + // ... + wordToNum('Two'); + ``` + - **CommonJS module require**: ```js @@ -189,9 +203,12 @@ As a library author, we want it to be compatible in different environments, i.e. Let's update the `output.library` option with its `type` set to [`'umd'`](/configuration/output/#type-umd): ```diff - const path = require('path'); + import path from 'path'; + import { fileURLToPath } from 'url'; + + const __dirname = path.dirname(fileURLToPath(import.meta.url)); - module.exports = { + export default { entry: './src/index.js', output: { path: path.resolve(__dirname, 'dist'), @@ -219,9 +236,11 @@ This can be done using the [`externals`](/configuration/externals/) configuratio **webpack.config.js** ```diff - const path = require('path'); + import path from 'path'; + import { fileURLToPath } from 'url'; - module.exports = { + const __dirname = path.dirname(fileURLToPath(import.meta.url)); + export default { entry: './src/index.js', output: { path: path.resolve(__dirname, 'dist'), @@ -237,6 +256,7 @@ This can be done using the [`externals`](/configuration/externals/) configuratio + commonjs2: 'lodash', + amd: 'lodash', + root: '_', + module: 'lodash', + }, + }, }; @@ -258,7 +278,7 @@ import B from 'library/two'; You won't be able to exclude them from the bundle by specifying `library` in the externals. You'll either need to exclude them one by one or by using a regular expression. ```js -module.exports = { +export default { //... externals: [ 'library/one', diff --git a/src/content/guides/build-performance.mdx b/src/content/guides/build-performance.mdx index 2e3a8689cda4..af6123374d27 100644 --- a/src/content/guides/build-performance.mdx +++ b/src/content/guides/build-performance.mdx @@ -31,7 +31,7 @@ Staying up-to-date with **Node.js** can also help with performance. On top of th Apply loaders to the minimal number of modules necessary. Instead of: ```js -module.exports = { +export default { //... module: { rules: [ @@ -47,9 +47,12 @@ module.exports = { Use the `include` field to only apply the loader modules that actually need to be transformed by it: ```js -const path = require('path'); +import path from 'path'; +import { fileURLToPath } from 'url'; -module.exports = { +const __dirname = path.dirname(fileURLToPath(import.meta.url)); + +export default { //... module: { rules: [ @@ -160,7 +163,7 @@ Webpack only emits updated chunks to the filesystem. For some configuration opti Make sure the entry chunk is cheap to emit by keeping it small. The following configuration creates an additional chunk for the runtime code, so it's cheap to generate: ```js -module.exports = { +export default { // ... optimization: { runtimeChunk: true, @@ -173,7 +176,7 @@ module.exports = { Webpack does extra algorithmic work to optimize the output for size and load performance. These optimizations are performant for smaller codebases, but can be costly in larger ones: ```js -module.exports = { +export default { // ... optimization: { removeAvailableModules: false, @@ -188,7 +191,7 @@ module.exports = { Webpack has the ability to generate path info in the output bundle. However, this puts garbage collection pressure on projects that bundle thousands of modules. Turn this off in the `options.output.pathinfo` setting: ```js -module.exports = { +export default { // ... output: { pathinfo: false, @@ -207,7 +210,7 @@ Earlier and later Node.js versions are not affected. To improve the build time when using `ts-loader`, use the `transpileOnly` loader option. On its own, this option turns off type checking. To gain type checking again, use the [`ForkTsCheckerWebpackPlugin`](https://www.npmjs.com/package/fork-ts-checker-webpack-plugin). This speeds up TypeScript type checking and ESLint linting by moving each to a separate process. ```js -module.exports = { +export default { // ... test: /\.tsx?$/, use: [ diff --git a/src/content/guides/caching.mdx b/src/content/guides/caching.mdx index 69b744564f46..a4acda49e6a9 100644 --- a/src/content/guides/caching.mdx +++ b/src/content/guides/caching.mdx @@ -47,10 +47,13 @@ webpack-demo **webpack.config.js** ```diff - const path = require('path'); - const HtmlWebpackPlugin = require('html-webpack-plugin'); + import path from 'path'; + import { fileURLToPath } from 'url'; + import HtmlWebpackPlugin from 'html-webpack-plugin'; - module.exports = { + const __dirname = path.dirname(fileURLToPath(import.meta.url)); + + export default { entry: './src/index.js', plugins: [ new HtmlWebpackPlugin({ @@ -98,10 +101,13 @@ As we learned in [code splitting](/guides/code-splitting), the [`SplitChunksPlug **webpack.config.js** ```diff - const path = require('path'); - const HtmlWebpackPlugin = require('html-webpack-plugin'); + import path from 'path'; + import { fileURLToPath } from 'url'; + import HtmlWebpackPlugin from 'html-webpack-plugin'; + + const __dirname = path.dirname(fileURLToPath(import.meta.url)); - module.exports = { + export default { entry: './src/index.js', plugins: [ new HtmlWebpackPlugin({ @@ -141,10 +147,13 @@ This can be done by using the [`cacheGroups`](/plugins/split-chunks-plugin/#spli **webpack.config.js** ```diff - const path = require('path'); - const HtmlWebpackPlugin = require('html-webpack-plugin'); + import path from 'path'; + import { fileURLToPath } from 'url'; + import HtmlWebpackPlugin from 'html-webpack-plugin'; - module.exports = { + const __dirname = path.dirname(fileURLToPath(import.meta.url)); + + export default { entry: './src/index.js', plugins: [ new HtmlWebpackPlugin({ @@ -253,10 +262,13 @@ The first and last are expected, it's the `vendor` hash we want to fix. Let's us **webpack.config.js** ```diff - const path = require('path'); - const HtmlWebpackPlugin = require('html-webpack-plugin'); + import path from 'path'; + import { fileURLToPath } from 'url'; + import HtmlWebpackPlugin from 'html-webpack-plugin'; + + const __dirname = path.dirname(fileURLToPath(import.meta.url)); - module.exports = { + export default { entry: './src/index.js', plugins: [ new HtmlWebpackPlugin({ diff --git a/src/content/guides/code-splitting.mdx b/src/content/guides/code-splitting.mdx index 0eff013ab4a9..376e99938c2e 100644 --- a/src/content/guides/code-splitting.mdx +++ b/src/content/guides/code-splitting.mdx @@ -83,9 +83,12 @@ console.log(_.join(['Another', 'module', 'loaded!'], ' ')); **webpack.config.js** ```diff - const path = require('path'); + import path from 'path'; + import { fileURLToPath } from 'url'; - module.exports = { + const __dirname = path.dirname(fileURLToPath(import.meta.url)); + + export default { - entry: './src/index.js', + mode: 'development', + entry: { @@ -131,9 +134,12 @@ The [`dependOn` option](/configuration/entry-context/#dependencies) allows to sh **webpack.config.js** ```diff - const path = require('path'); + import path from 'path'; + import { fileURLToPath } from 'url'; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); - module.exports = { + export default { mode: 'development', entry: { - index: './src/index.js', @@ -160,9 +166,12 @@ If we're going to use multiple entry points on a single HTML page, `optimization **webpack.config.js** ```diff - const path = require('path'); + import path from 'path'; + import { fileURLToPath } from 'url'; + + const __dirname = path.dirname(fileURLToPath(import.meta.url)); - module.exports = { + export default { mode: 'development', entry: { index: { @@ -216,9 +225,12 @@ The [`SplitChunksPlugin`](/plugins/split-chunks-plugin/) allows us to extract co **webpack.config.js** ```diff - const path = require('path'); + import path from 'path'; + import { fileURLToPath } from 'url'; - module.exports = { + const __dirname = path.dirname(fileURLToPath(import.meta.url)); + + export default { mode: 'development', entry: { index: './src/index.js', @@ -271,9 +283,12 @@ Before we start, let's remove the extra [`entry`](/concepts/entry-points/) and [ **webpack.config.js** ```diff - const path = require('path'); + import path from 'path'; + import { fileURLToPath } from 'url'; + + const __dirname = path.dirname(fileURLToPath(import.meta.url)); - module.exports = { + export default { mode: 'development', entry: { index: './src/index.js', diff --git a/src/content/guides/development-vagrant.mdx b/src/content/guides/development-vagrant.mdx index 03b871fedb79..1539e4e54c2e 100644 --- a/src/content/guides/development-vagrant.mdx +++ b/src/content/guides/development-vagrant.mdx @@ -29,7 +29,12 @@ npm install --save-dev webpack webpack-cli @webpack-cli/serve webpack-dev-server Make sure to have a `webpack.config.js` file. If you haven't already, use this as a minimal example to get started: ```js -module.exports = { +import path from 'path'; +import { fileURLToPath } from 'url'; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); + +export default { context: __dirname, entry: './app.js', }; diff --git a/src/content/guides/development.mdx b/src/content/guides/development.mdx index 9d3eb00e684c..58cad60a646c 100644 --- a/src/content/guides/development.mdx +++ b/src/content/guides/development.mdx @@ -30,10 +30,14 @@ Let's start by setting [`mode` to `'development'`](/configuration/mode/#mode-dev **webpack.config.js** ```diff - const path = require('path'); - const HtmlWebpackPlugin = require('html-webpack-plugin'); + import path from 'path'; + import { fileURLToPath } from 'url'; + import HtmlWebpackPlugin from 'html-webpack-plugin'; - module.exports = { + const __dirname = path.dirname(fileURLToPath(import.meta.url)); + + + export default { + mode: 'development', entry: { index: './src/index.js', @@ -66,10 +70,13 @@ For this guide, let's use the `inline-source-map` option, which is good for illu **webpack.config.js** ```diff - const path = require('path'); - const HtmlWebpackPlugin = require('html-webpack-plugin'); + import path from 'path'; + import { fileURLToPath } from 'url'; + import HtmlWebpackPlugin from 'html-webpack-plugin'; + + const __dirname = path.dirname(fileURLToPath(import.meta.url)); - module.exports = { + export default { mode: 'development', entry: { index: './src/index.js', @@ -203,10 +210,13 @@ Change your configuration file to tell the dev server where to look for files: **webpack.config.js** ```diff - const path = require('path'); - const HtmlWebpackPlugin = require('html-webpack-plugin'); + import path from 'path'; + import { fileURLToPath } from 'url'; + import HtmlWebpackPlugin from 'html-webpack-plugin'; - module.exports = { + const __dirname = path.dirname(fileURLToPath(import.meta.url)); + + export default { mode: 'development', entry: { index: './src/index.js', @@ -292,10 +302,13 @@ Now we need to make some adjustments to our webpack configuration file in order **webpack.config.js** ```diff - const path = require('path'); - const HtmlWebpackPlugin = require('html-webpack-plugin'); + import path from 'path'; + import { fileURLToPath } from 'url'; + import HtmlWebpackPlugin from 'html-webpack-plugin'; + + const __dirname = path.dirname(fileURLToPath(import.meta.url)); - module.exports = { + export default { mode: 'development', entry: { index: './src/index.js', @@ -339,12 +352,12 @@ The `publicPath` will be used within our server script as well in order to make **server.js** ```javascript -const express = require('express'); -const webpack = require('webpack'); -const webpackDevMiddleware = require('webpack-dev-middleware'); +import express from 'express'; +import webpack from 'webpack'; +import webpackDevMiddleware from 'webpack-dev-middleware'; const app = express(); -const config = require('./webpack.config.js'); +import config from './webpack.config.js'; const compiler = webpack(config); // Tell express to use the webpack-dev-middleware and use the webpack.config.js diff --git a/src/content/guides/entry-advanced.mdx b/src/content/guides/entry-advanced.mdx index 40198b05dc9e..b0ecae4f1ae0 100644 --- a/src/content/guides/entry-advanced.mdx +++ b/src/content/guides/entry-advanced.mdx @@ -40,9 +40,9 @@ We will use [`MiniCssExtractPlugin`](/plugins/mini-css-extract-plugin/) in `prod **webpack.config.js** ```js -const MiniCssExtractPlugin = require('mini-css-extract-plugin'); +import MiniCssExtractPlugin from 'mini-css-extract-plugin'; -module.exports = { +export default { mode: process.env.NODE_ENV, entry: { home: ['./home.js', './home.scss'], diff --git a/src/content/guides/environment-variables.mdx b/src/content/guides/environment-variables.mdx index 04d36de0aca3..345bc2ad9b10 100644 --- a/src/content/guides/environment-variables.mdx +++ b/src/content/guides/environment-variables.mdx @@ -28,9 +28,12 @@ There is one change that you will have to make to your webpack config. Typically **webpack.config.js** ```js -const path = require('path'); +import path from 'path'; +import { fileURLToPath } from 'url'; -module.exports = (env) => { +const __dirname = path.dirname(fileURLToPath(import.meta.url)); + +export default (env) => { // Use env. here: console.log('Goal: ', env.goal); // 'local' console.log('Production: ', env.production); // true diff --git a/src/content/guides/hot-module-replacement.mdx b/src/content/guides/hot-module-replacement.mdx index cfed0bc16a64..744980d5d668 100644 --- a/src/content/guides/hot-module-replacement.mdx +++ b/src/content/guides/hot-module-replacement.mdx @@ -46,10 +46,13 @@ T> If you took the route of using `webpack-dev-middleware` instead of `webpack-d **webpack.config.js** ```diff - const path = require('path'); - const HtmlWebpackPlugin = require('html-webpack-plugin'); + import path from 'path'; + import HtmlWebpackPlugin from 'html-webpack-plugin'; - module.exports = { + import { fileURLToPath } from 'url'; + const __dirname = path.dirname(fileURLToPath(import.meta.url)); + + export default { entry: { app: './src/index.js', - print: './src/print.js', @@ -77,11 +80,15 @@ you can also provide manual entry points for HMR: **webpack.config.js** ```diff - const path = require('path'); - const HtmlWebpackPlugin = require('html-webpack-plugin'); -+ const webpack = require("webpack"); + import path from 'path'; + import HtmlWebpackPlugin from 'html-webpack-plugin'; + + import { fileURLToPath } from 'url'; + const __dirname = path.dirname(fileURLToPath(import.meta.url)); - module.exports = { ++ import webpack from 'webpack'; + + export default { entry: { app: './src/index.js', - print: './src/print.js', @@ -182,11 +189,11 @@ To enable HMR, you also need to modify your webpack configuration object to incl **dev-server.js** ```javascript -const path = require('path'); -const HtmlWebpackPlugin = require('html-webpack-plugin'); +import path from 'path'; +import HtmlWebpackPlugin from 'html-webpack-plugin'; -const webpack = require('webpack'); -const webpackDevServer = require('webpack-dev-server'); +import webpack from 'webpack'; +import webpackDevServer from 'webpack-dev-server'; const config = { mode: 'development', @@ -287,10 +294,13 @@ Now let's update the configuration file to make use of the loader. **webpack.config.js** ```diff - const path = require('path'); - const HtmlWebpackPlugin = require('html-webpack-plugin'); + import path from 'path'; + import HtmlWebpackPlugin from 'html-webpack-plugin'; + + import { fileURLToPath } from 'url'; + const __dirname = path.dirname(fileURLToPath(import.meta.url)); - module.exports = { + export default { entry: { app: './src/index.js', }, diff --git a/src/content/guides/integrations.mdx b/src/content/guides/integrations.mdx index 066d1f9452a3..b46cccc2eaa2 100644 --- a/src/content/guides/integrations.mdx +++ b/src/content/guides/integrations.mdx @@ -34,9 +34,8 @@ Then register a configuration and load the task: **Gruntfile.js** ```js -const webpackConfig = require('./webpack.config.js'); - -module.exports = function (grunt) { +export default async function (grunt) { + const { default: webpackConfig } = await import('./webpack.config.js'); grunt.initConfig({ webpack: { options: { @@ -48,7 +47,7 @@ module.exports = function (grunt) { }); grunt.loadNpmTasks('grunt-webpack'); -}; +} ``` For more information, please visit the [repository](https://github.com/webpack/grunt-webpack). @@ -66,8 +65,8 @@ You can `require('webpack-stream')` instead of `webpack` and optionally pass it **gulpfile.js** ```js -const gulp = require('gulp'); -const webpack = require('webpack-stream'); +import gulp from 'gulp'; +import webpack from 'webpack-stream'; gulp.task('default', function () { return gulp .src('src/entry.js') @@ -104,7 +103,7 @@ npm install --save-dev webpack karma karma-webpack **karma.conf.js** ```js -module.exports = function (config) { +export default function (config) { config.set({ frameworks: ['webpack'], files: [ @@ -120,7 +119,7 @@ module.exports = function (config) { }, plugins: ['karma-webpack'], }); -}; +} ``` For more information, please visit the [repository](https://github.com/webpack-contrib/karma-webpack). diff --git a/src/content/guides/output-management.mdx b/src/content/guides/output-management.mdx index 226c20a72614..5e7fb959d8ef 100644 --- a/src/content/guides/output-management.mdx +++ b/src/content/guides/output-management.mdx @@ -94,9 +94,12 @@ Now adjust the config. We'll be adding our `src/print.js` as a new entry point ( **webpack.config.js** ```diff - const path = require('path'); + import path from 'path'; + import { fileURLToPath } from 'url'; - module.exports = { + const __dirname = path.dirname(fileURLToPath(import.meta.url)); + + export default { - entry: './src/index.js', + entry: { + index: './src/index.js', @@ -140,10 +143,13 @@ npm install --save-dev html-webpack-plugin **webpack.config.js** ```diff - const path = require('path'); -+const HtmlWebpackPlugin = require('html-webpack-plugin'); + import path from 'path'; ++import { fileURLToPath } from 'url'; + import HtmlWebpackPlugin from 'html-webpack-plugin'; + + const __dirname = path.dirname(fileURLToPath(import.meta.url)); - module.exports = { + export default { entry: { index: './src/index.js', print: './src/print.js', @@ -189,10 +195,13 @@ In general it's good practice to clean the `/dist` folder before each build, so **webpack.config.js** ```diff - const path = require('path'); - const HtmlWebpackPlugin = require('html-webpack-plugin'); + import path from 'path'; + import { fileURLToPath } from 'url'; + import HtmlWebpackPlugin from 'html-webpack-plugin'; + + const __dirname = path.dirname(fileURLToPath(import.meta.url)); - module.exports = { + export default { entry: { index: './src/index.js', print: './src/print.js', diff --git a/src/content/guides/package-exports.mdx b/src/content/guides/package-exports.mdx index 55e1224f5cc4..cffe3265a056 100644 --- a/src/content/guides/package-exports.mdx +++ b/src/content/guides/package-exports.mdx @@ -500,9 +500,9 @@ Otherwise, in production or when mode is unknown, we use the optimized version. ```js // wrapper-process-env.cjs if (process.env.NODE_ENV !== 'development') { - module.exports = require('./index-optimized.cjs'); + export default require('./index-optimized.cjs'); } else { - module.exports = require('./index-with-devtools.cjs'); + export default require('./index-with-devtools.cjs'); } ``` diff --git a/src/content/guides/production.mdx b/src/content/guides/production.mdx index e211d44d1e92..c384b176e39c 100644 --- a/src/content/guides/production.mdx +++ b/src/content/guides/production.mdx @@ -61,10 +61,13 @@ npm install --save-dev webpack-merge **webpack.common.js** ```diff -+ const path = require('path'); -+ const HtmlWebpackPlugin = require('html-webpack-plugin'); ++ import path from 'path'; ++ import { fileURLToPath } from 'url'; + import HtmlWebpackPlugin from 'html-webpack-plugin'; + + const __dirname = path.dirname(fileURLToPath(import.meta.url)); + -+ module.exports = { ++ export default { + entry: { + app: './src/index.js', + }, @@ -84,10 +87,10 @@ npm install --save-dev webpack-merge **webpack.dev.js** ```diff -+ const { merge } = require('webpack-merge'); -+ const common = require('./webpack.common.js'); ++ import { merge } from 'webpack-merge'; ++ import common from './webpack.common.js'; + -+ module.exports = merge(common, { ++ export default merge(common, { + mode: 'development', + devtool: 'inline-source-map', + devServer: { @@ -99,10 +102,10 @@ npm install --save-dev webpack-merge **webpack.prod.js** ```diff -+ const { merge } = require('webpack-merge'); -+ const common = require('./webpack.common.js'); ++ import { merge } from 'webpack-merge'; ++ import common from './webpack.common.js'; + -+ module.exports = merge(common, { ++ export default merge(common, { + mode: 'production', + }); ``` @@ -160,7 +163,7 @@ Many libraries will key off the `process.env.NODE_ENV` variable to determine wha const { merge } = require('webpack-merge'); const common = require('./webpack.common.js'); - module.exports = merge(common, { + export default merge(common, { mode: 'production', }); ``` @@ -212,7 +215,7 @@ We encourage you to have source maps enabled in production, as they are useful f const { merge } = require('webpack-merge'); const common = require('./webpack.common.js'); - module.exports = merge(common, { + export default merge(common, { mode: 'production', + devtool: 'source-map', }); diff --git a/src/content/guides/progressive-web-application.mdx b/src/content/guides/progressive-web-application.mdx index 79e957837ff6..bf62bd4d6f6d 100644 --- a/src/content/guides/progressive-web-application.mdx +++ b/src/content/guides/progressive-web-application.mdx @@ -65,11 +65,14 @@ npm install workbox-webpack-plugin --save-dev **webpack.config.js** ```diff - const path = require('path'); - const HtmlWebpackPlugin = require('html-webpack-plugin'); -+ const WorkboxPlugin = require('workbox-webpack-plugin'); + import path from 'path'; + import { fileURLToPath } from 'url'; + import HtmlWebpackPlugin from 'html-webpack-plugin'; ++ import WorkboxPlugin from 'workbox-webpack-plugin'; - module.exports = { + const __dirname = path.dirname(fileURLToPath(import.meta.url)); + + export default { entry: { app: './src/index.js', print: './src/print.js', diff --git a/src/content/guides/public-path.mdx b/src/content/guides/public-path.mdx index cea41808d39f..fb63da4d6464 100644 --- a/src/content/guides/public-path.mdx +++ b/src/content/guides/public-path.mdx @@ -67,7 +67,7 @@ There are chances that you don't know what the publicPath will be in advance, an **webpack.config.js** ```js -module.exports = { +export default { output: { publicPath: 'auto', }, diff --git a/src/content/guides/shimming.mdx b/src/content/guides/shimming.mdx index 27e6a9f25166..8e755afeb766 100644 --- a/src/content/guides/shimming.mdx +++ b/src/content/guides/shimming.mdx @@ -75,10 +75,13 @@ The [`ProvidePlugin`](/plugins/provide-plugin) makes a package available as a va **webpack.config.js** ```diff - const path = require('path'); -+const webpack = require('webpack'); + import path from 'path'; + import { fileURLToPath } from 'url'; ++import webpack from 'webpack'; - module.exports = { + const __dirname = path.dirname(fileURLToPath(import.meta.url)); + + export default { entry: './src/index.js', output: { filename: 'main.js', @@ -132,10 +135,11 @@ We can also use the `ProvidePlugin` to expose a single export of a module by con **webpack.config.js** ```diff - const path = require('path'); - const webpack = require('webpack'); - - module.exports = { + import path from 'path'; + import { fileURLToPath } from 'url'; + import webpack from 'webpack'; + const __dirname = path.dirname(fileURLToPath(import.meta.url)); + export default { entry: './src/index.js', output: { filename: 'main.js', @@ -176,10 +180,13 @@ This becomes a problem when the module is executed in a CommonJS context where ` **webpack.config.js** ```diff - const path = require('path'); - const webpack = require('webpack'); + import path from 'path'; + import { fileURLToPath } from 'url'; + import webpack from 'webpack'; + + const __dirname = path.dirname(fileURLToPath(import.meta.url)); - module.exports = { + export default { entry: './src/index.js', output: { filename: 'main.js', @@ -238,10 +245,12 @@ Now, while you'd likely never do this in your own source code, you may encounter **webpack.config.js** ```diff - const path = require('path'); - const webpack = require('webpack'); + import path from 'path'; + import { fileURLToPath } from 'url'; + import webpack from 'webpack'; + const __dirname = path.dirname(fileURLToPath(import.meta.url)); - module.exports = { + export default { entry: './src/index.js', output: { filename: 'main.js', @@ -358,10 +367,12 @@ import 'whatwg-fetch'; **webpack.config.js** ```diff - const path = require('path'); - const webpack = require('webpack'); + import path from 'path'; + import { fileURLToPath } from 'url'; + import webpack from 'webpack'; - module.exports = { + const __dirname = path.dirname(fileURLToPath(import.meta.url)); + export default { - entry: './src/index.js', + entry: { + polyfills: './src/polyfills', diff --git a/src/content/guides/tree-shaking.mdx b/src/content/guides/tree-shaking.mdx index c76cad1f9d71..8d481a266c1c 100644 --- a/src/content/guides/tree-shaking.mdx +++ b/src/content/guides/tree-shaking.mdx @@ -69,9 +69,12 @@ Set the `mode` configuration option to [development](/configuration/mode/#mode-d **webpack.config.js** ```diff -const path = require('path'); +import path from 'path'; +import { fileURLToPath } from 'url'; -module.exports = { +const __dirname = path.dirname(fileURLToPath(import.meta.url)); + +export default { entry: './src/index.js', output: { filename: 'bundle.js', @@ -457,7 +460,6 @@ With this configuration: Here's how webpack evaluates modules during tree shaking: 1. Is the export from this module used directly or indirectly? - - If yes: Include the module - If no: Continue to step 2 @@ -512,9 +514,12 @@ So we've cued up our "dead code" to be dropped by using the `import` and `export **webpack.config.js** ```diff -const path = require('path'); +import path from 'path'; +import { fileURLToPath } from 'url'; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); -module.exports = { +export default { entry: './src/index.js', output: { filename: 'bundle.js', diff --git a/src/content/guides/typescript.mdx b/src/content/guides/typescript.mdx index 1694bb2bb711..d12e426334fb 100644 --- a/src/content/guides/typescript.mdx +++ b/src/content/guides/typescript.mdx @@ -69,9 +69,12 @@ Now let's configure webpack to handle TypeScript: **webpack.config.js** ```js -const path = require('path'); +import path from 'path'; +import { fileURLToPath } from 'url'; -module.exports = { +const __dirname = path.dirname(fileURLToPath(import.meta.url)); + +export default { entry: './src/index.ts', module: { rules: [ @@ -189,9 +192,12 @@ Now we need to tell webpack to extract these source maps and include in our fina **webpack.config.js** ```diff - const path = require('path'); + import path from 'path'; + import { fileURLToPath } from 'url'; + + const __dirname = path.dirname(fileURLToPath(import.meta.url)); - module.exports = { + export default { entry: './src/index.ts', + devtool: 'inline-source-map', module: { diff --git a/src/content/migrate/3.mdx b/src/content/migrate/3.mdx index dec239634b6a..787d0825d5d5 100644 --- a/src/content/migrate/3.mdx +++ b/src/content/migrate/3.mdx @@ -27,6 +27,10 @@ T> Note that there were far fewer changes between 2 and 3, so that migration sho These options were replaced by a single option `resolve.modules`. See [resolving](/configuration/resolve) for more usage. ```diff + import path from 'path'; + import { fileURLToPath } from 'url'; + + const __dirname = path.dirname(fileURLToPath(import.meta.url)); resolve: { - root: path.join(__dirname, "src") + modules: [ @@ -229,6 +233,8 @@ The minimize mode for loaders will be removed in webpack 3 or later. To keep compatibility with old loaders, loaders can be switched to minimize mode via plugin: ```diff + import webpack from 'webpack'; + plugins: [ + new webpack.LoaderOptionsPlugin({ + minimize: true @@ -245,6 +251,8 @@ To keep compatibility with old loaders, loaders can be switched to minimize mode `BannerPlugin` no longer accepts two parameters, but a single options object. ```diff + import webpack from 'webpack'; + plugins: [ - new webpack.BannerPlugin('Banner', {raw: true, entryOnly: true}); + new webpack.BannerPlugin({banner: 'Banner', raw: true, entryOnly: true}); @@ -294,6 +302,8 @@ module: { ### `new ExtractTextPlugin({options})` ```diff +import ExtractTextPlugin from 'extract-text-webpack-plugin'; + plugins: [ - new ExtractTextPlugin("bundle.css", { allChunks: true, disable: false }) + new ExtractTextPlugin({ @@ -322,7 +332,7 @@ If you abused the CLI to pass custom arguments to the configuration like so: // webpack.config.js var customStuff = process.argv.indexOf('--custom-stuff') >= 0; /* ... */ -module.exports = config; +export default config; ``` You may notice that this is no longer allowed. The CLI is more strict now. @@ -332,11 +342,11 @@ Instead there is an interface for passing arguments to the configuration. This s `webpack --env.customStuff` ```js -module.exports = function (env) { +export default function (env) { var customStuff = env.customStuff; /* ... */ return config; -}; +} ``` See [CLI](/api/cli). @@ -352,7 +362,7 @@ These functions are now always asynchronous instead of calling their callback sy You can _no longer_ configure a loader with a custom property in the `webpack.config.js`. It must be done through the `options`. The following configuration with the `ts` property is no longer valid with webpack 2: ```js -module.exports = { +export default { //... module: { rules: [ @@ -372,7 +382,7 @@ module.exports = { Good question. Well, strictly speaking it's 2 possible things; both ways to configure a webpack loader. Classically `options` was called `query` and was a string which could be appended to the name of the loader. Much like a query string but actually with [greater powers](https://github.com/webpack/loader-utils#parsequery): ```js -module.exports = { +export default { //... module: { rules: [ @@ -388,7 +398,7 @@ module.exports = { But it can also be a separately specified object that's supplied alongside a loader: ```js -module.exports = { +export default { //... module: { rules: [ @@ -528,13 +538,13 @@ Webpack now supports returning a `Promise` from the configuration file. This all **webpack.config.js** ```js -module.exports = function () { +export default function () { return fetchLangs().then((lang) => ({ entry: '...', // ... plugins: [new DefinePlugin({ LANGUAGE: lang })], })); -}; +} ``` ### Advanced loader matching @@ -542,7 +552,7 @@ module.exports = function () { Webpack now supports more things to match on for loaders. ```js -module.exports = { +export default { //... module: { rules: [ @@ -580,7 +590,7 @@ Loaders are now cacheable by default. Loaders must opt-out if they are not cache ```diff // Cacheable loader - module.exports = function(source) { + export default function(source) { - this.cacheable(); return source; } @@ -588,7 +598,7 @@ Loaders are now cacheable by default. Loaders must opt-out if they are not cache ```diff // Not cacheable loader - module.exports = function(source) { + export default function(source) { + this.cacheable(false); return source; } diff --git a/src/content/migrate/4.mdx b/src/content/migrate/4.mdx index 65ae899b142e..2375327df7d1 100644 --- a/src/content/migrate/4.mdx +++ b/src/content/migrate/4.mdx @@ -39,7 +39,7 @@ Add the new [`mode`](/configuration/mode/) option to your configuration. Set it **webpack.config.js** ```diff -module.exports = { +export default { // ... + mode: 'production', } @@ -54,7 +54,7 @@ These plugins can be removed from configuration as they are default in productio **webpack.config.js** ```diff -module.exports = { +export default { // ... plugins: [ - new NoEmitOnErrorsPlugin(), @@ -70,7 +70,7 @@ These plugins are default in development mode **webpack.config.js** ```diff -module.exports = { +export default { // ... plugins: [ - new NamedModulesPlugin() @@ -83,7 +83,7 @@ These plugins were deprecated and are now removed: **webpack.config.js** ```diff -module.exports = { +export default { // ... plugins: [ - new NoErrorsPlugin(), @@ -107,7 +107,7 @@ When using `import()` to load non-ESM the result has changed in webpack 4. Now y **non-esm.js** ```javascript -module.exports = { +export default { sayHello: () => { console.log('hello world'); }, @@ -131,7 +131,7 @@ When using a custom loader to transform `.json` files you now need to change the **webpack.config.js** ```diff -module.exports = { +export default { // ... rules: [ { @@ -149,7 +149,7 @@ When still using the `json-loader`, it can be removed: **webpack.config.js** ```diff -module.exports = { +export default { // ... rules: [ { diff --git a/src/content/migrate/5.mdx b/src/content/migrate/5.mdx index b4801396d844..a3254b69f7b5 100644 --- a/src/content/migrate/5.mdx +++ b/src/content/migrate/5.mdx @@ -25,7 +25,6 @@ Webpack 5 requires at least Node.js 10.13.0 (LTS), so make sure you upgrade your ## Upgrade webpack 4 and its plugins/loaders 1. Upgrade `webpack` 4 to the latest available version. - - When using webpack >= 4, upgrading to the latest webpack 4 version should not require additional guidance. - If you are using webpack version less than 4 please see the [webpack 4 migration guide](/migrate/4/). @@ -37,7 +36,6 @@ Webpack 5 requires at least Node.js 10.13.0 (LTS), so make sure you upgrade your Some Plugins and Loaders might have a beta version that has to be used in order to be compatible with webpack 5. Make sure to read release notes of each individual plugin/loader when upgrading it, since latest version might only support webpack 5 and will fail in v4. In such case, it's recommended to update to the latest version that supports webpack 4. - ## Codemods To assist with the upgrade from webpack v4 to v5, [Codemod](https://github.com/codemod-com/codemod) provides open-source community codemods that can help automate most of the migration process. @@ -100,13 +98,17 @@ T> Checkout the detailed changes in the configuration options [here](/blog/2020- Try to set the following options in your webpack 4 configuration and check if build still works correctly. ```javascript -module.exports = { - // ... - node: { - Buffer: false, - process: false, - }, -}; ++import path from 'path'; ++import { fileURLToPath } from 'url'; + ++const __dirname = path.dirname(fileURLToPath(import.meta.url)); + export default { + // ... + node: { + Buffer: false, + process: false, + }, + }; ``` You have to remove these options again when upgrading your configuration for webpack 5. @@ -209,7 +211,6 @@ Consider removing defaults: - If you have [browserslist](https://github.com/browserslist/browserslist) enabled for your project, webpack 5 will reuse your `browserslist` config to decide which code style to emit for the runtime code. Make sure to: - 1. set [`target`](/configuration/target/#root) to `browserslist` or remove `target` letting webpack set `browserslist` automatically for you. 2. add a `IE 11` to your browserslist configuration. @@ -243,13 +244,13 @@ import pkg from './package.json'; console.log(pkg.version); ``` - > **Note**: Codemod for this change: - > - > ```bash - > npx codemod webpack/v5/json-imports-to-default-imports - > ``` - > - > (See the [registry here](https://codemod.com/registry/webpack-v5-json-imports-to-default-imports).) +> **Note**: Codemod for this change: +> +> ```bash +> npx codemod webpack/v5/json-imports-to-default-imports +> ``` +> +> (See the [registry here](https://codemod.com/registry/webpack-v5-json-imports-to-default-imports).) #### Cleanup the build code @@ -282,7 +283,6 @@ Repeat the following steps until you solved at least level 3 or 4: - Level 5: **Runtime Errors**. This is tricky. You probably have to debug to find the problem. General advice is difficult here. But we do list some common advice below regarding Runtime Errors: - - `process` is not defined. - webpack 5 does no longer include a polyfill for this Node.js variable. Avoid using it in the frontend code. - Want to support browser usage? Use the `exports` or `imports` package.json field to use different code depending on the environment. @@ -295,13 +295,12 @@ Repeat the following steps until you solved at least level 3 or 4: - Use a static `output.publicPath: ""` instead. - Cannot read properties of undefined (reading 'call') - If you see this error during runtime, it may be related to the [ModuleConcatenationPlugin](https://webpack.js.org/plugins/module-concatenation-plugin/). Check if you are using the plugin, and if you've included it in the `plugins` sections of a config, and that config is also set to `production` mode, remove the plugin (ie `new webpack.optimize.ModuleConcatenationPlugin()`) from your plugins list. In webpack 5, the plugin is enabled by default in production mode, and it may get included twice. - - In general, disabling each plugin and testing the build is a good way to triage where the issue might be coming from. + - In general, disabling each plugin and testing the build is a good way to triage where the issue might be coming from. - See: [this issue](https://github.com/webpack/webpack/discussions/15369#discussioncomment-13420496) for more details. - Level 6: **Deprecation Warnings**. You probably get a lot of deprecation warnings. This is not directly a problem. Plugins need time to catch up with core changes. Please report these deprecations to the plugins. These deprecations are only warnings and the build will still work with only minor drawbacks (like less performance). - - You can hide deprecation warnings by running node with `--no-deprecation` flag, e.g.: `node --no-deprecation node_modules/webpack/bin/webpack.js`. This should only be a temporary workaround. - Plugins and Loaders contributors can follow the advice in the deprecation messages to improve the code. @@ -310,7 +309,6 @@ Repeat the following steps until you solved at least level 3 or 4: Usually, performance should improve with webpack 5, but there are also a few cases where performance gets worse. And here are something you can do to improve the situation: - - Profile where the time is spent. - `--profile --progress` displays a simple performance profile now - `node --inspect-brk node_modules/webpack/bin/webpack.js` + [`chrome://inspect`](chrome://inspect) / [`edge://inspect`](edge://inspect) (see profiler tab). diff --git a/src/content/plugins/NoEmitOnErrorsPlugin.mdx b/src/content/plugins/NoEmitOnErrorsPlugin.mdx index 11522eb933a2..91ce834053e4 100644 --- a/src/content/plugins/NoEmitOnErrorsPlugin.mdx +++ b/src/content/plugins/NoEmitOnErrorsPlugin.mdx @@ -12,7 +12,9 @@ The `NoEmitOnErrorsPlugin` allows you to avoid emitting assets when there are an **webpack.config.js** ```javascript -module.exports = { +import webpack from 'webpack'; + +export default { plugins: [new webpack.NoEmitOnErrorsPlugin()], }; ``` diff --git a/src/content/plugins/automatic-prefetch-plugin.mdx b/src/content/plugins/automatic-prefetch-plugin.mdx index 78881e3d7ea4..98aaacf1d70b 100644 --- a/src/content/plugins/automatic-prefetch-plugin.mdx +++ b/src/content/plugins/automatic-prefetch-plugin.mdx @@ -13,8 +13,9 @@ W> May or may not have a performance benefit since the incremental build times a **webpack.config.js** ```javascript -module.exports = { - // ... - plugins: [new webpack.AutomaticPrefetchPlugin()], -}; ++import webpack from 'webpack'; + export default { + // ... + plugins: [new webpack.AutomaticPrefetchPlugin()], + }; ``` diff --git a/src/content/plugins/commons-chunk-plugin.mdx b/src/content/plugins/commons-chunk-plugin.mdx index a6f1b506421a..d41c42bf2d70 100644 --- a/src/content/plugins/commons-chunk-plugin.mdx +++ b/src/content/plugins/commons-chunk-plugin.mdx @@ -75,6 +75,8 @@ new webpack.optimize.CommonsChunkPlugin(options); Generate an extra chunk, which contains common modules shared between entry points. ```javascript +import webpack from 'webpack'; + new webpack.optimize.CommonsChunkPlugin({ name: 'commons', // (the commons chunk name) @@ -102,7 +104,9 @@ You must load the generated chunk before the entry point: Split your code into vendor and application. ```javascript -module.exports = { +import webpack from 'webpack'; + +export default { //... entry: { vendor: ['jquery', 'other-lib'], @@ -134,6 +138,8 @@ T> In combination with long term caching you may need to use the [`ChunkManifest With [Code Splitting](/guides/code-splitting), multiple child chunks of an entry chunk can have common dependencies. To prevent duplication these can be moved into the parent. This reduces overall size, but does have a negative effect on the initial load time. If it is expected that users will need to download many sibling chunks, i.e. children of the entry chunk, then this should improve load time overall. ```javascript +import webpack from 'webpack'; + new webpack.optimize.CommonsChunkPlugin({ // names: ["app", "subPageA"] // (choose the chunks, or omit for all chunks) @@ -151,6 +157,8 @@ new webpack.optimize.CommonsChunkPlugin({ Similar to the above one, but instead of moving common modules into the parent (which increases initial load time) a new async-loaded additional commons chunk is used. This is automatically downloaded in parallel when the additional chunk is downloaded. ```javascript +import webpack from 'webpack'; + new webpack.optimize.CommonsChunkPlugin({ name: 'app', // or @@ -184,6 +192,8 @@ The `count` argument represents how many chunks the `module` is used in. This option is useful when you want to have fine-grained control over how the CommonsChunk algorithm determines where modules should be moved to. ```javascript +import webpack from 'webpack'; + new webpack.optimize.CommonsChunkPlugin({ name: 'my-single-lib-chunk', filename: 'my-single-lib-chunk.js', @@ -201,6 +211,8 @@ As seen above, this example allows you to move only one lib to a separate file i This concept may be used to obtain implicit common vendor chunks: ```javascript +import webpack from 'webpack'; + new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', minChunks: function (module) { @@ -215,6 +227,8 @@ new webpack.optimize.CommonsChunkPlugin({ To extract the webpack bootstrap logic into a separate file, use the `CommonsChunkPlugin` on a `name` which is not defined as `entry`. Commonly the name `manifest` is used. See the [caching guide](/guides/caching) for details. ```javascript +import webpack from 'webpack'; + new webpack.optimize.CommonsChunkPlugin({ name: 'manifest', minChunks: Infinity, @@ -226,6 +240,8 @@ new webpack.optimize.CommonsChunkPlugin({ Since the `vendor` and `manifest` chunk use a different definition for `minChunks`, you need to invoke the plugin twice: ```javascript +import webpack from 'webpack'; + [ new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', diff --git a/src/content/plugins/context-exclusion-plugin.mdx b/src/content/plugins/context-exclusion-plugin.mdx index ed2f4bcda680..632df01843c0 100644 --- a/src/content/plugins/context-exclusion-plugin.mdx +++ b/src/content/plugins/context-exclusion-plugin.mdx @@ -12,7 +12,9 @@ The `ContextExclusionPlugin` allows you to exclude context. Provide RegExp as an **webpack.config.js** ```javascript -module.exports = { - plugins: [new webpack.ContextExclusionPlugin(/dont/)], -}; ++import webpack from 'webpack'; + + export default { + plugins: [new webpack.ContextExclusionPlugin(/dont/)], + }; ``` diff --git a/src/content/plugins/define-plugin.mdx b/src/content/plugins/define-plugin.mdx index 9386dc6d4714..5bf9828ecbd3 100644 --- a/src/content/plugins/define-plugin.mdx +++ b/src/content/plugins/define-plugin.mdx @@ -107,7 +107,6 @@ There're two arguments for `webpack.DefinePlugin.runtimeValue` function: - The first argument is a `function(module, key, version)` that should return the value to be assigned to the definition. - The second argument could either be an array of file paths to watch for or a `true` to flag the module as uncacheable. Since 5.26.0, it can also take an object argument with the following properties: - - `fileDependencies?: string[]` A list of files the function depends on. - `contextDependencies?: string[]` A list of directories the function depends on. - `missingDependencies?: string[]` A list of not existing files the function depends on. diff --git a/src/content/plugins/dll-plugin.mdx b/src/content/plugins/dll-plugin.mdx index 9cb673202410..94d2a6ba1f60 100644 --- a/src/content/plugins/dll-plugin.mdx +++ b/src/content/plugins/dll-plugin.mdx @@ -30,6 +30,8 @@ This plugin is used in a separate webpack configuration exclusively to create a - `type`: type of the dll bundle ```javascript +import webpack from 'webpack'; + new webpack.DllPlugin(options); ``` @@ -54,6 +56,8 @@ This plugin is used in the primary webpack config, it references the dll-only-bu - `sourceType` (optional): how the dll is exposed ([libraryTarget](/configuration/output/#outputlibrarytarget)) ```javascript +import webpack from 'webpack'; + new webpack.DllReferencePlugin(options); ``` @@ -84,7 +88,11 @@ W> `DllReferencePlugin` and `DllPlugin` are used in _separate_ webpack configs. **webpack.vendor.config.js** ```javascript -const path = require('path'); +import path from 'path'; +import { fileURLToPath } from 'url'; +import webpack from 'webpack'; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); new webpack.DllPlugin({ context: __dirname, @@ -96,9 +104,15 @@ new webpack.DllPlugin({ **webpack.app.config.js** ```javascript +import { fileURLToPath } from 'url'; +import webpack from 'webpack'; +import manifest from './manifest.json' assert { type: 'json' }; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); + new webpack.DllReferencePlugin({ context: __dirname, - manifest: require('./manifest.json'), + manifest, scope: 'xyz', sourceType: 'commonjs2', }); diff --git a/src/content/plugins/eval-source-map-dev-tool-plugin.mdx b/src/content/plugins/eval-source-map-dev-tool-plugin.mdx index 5a207063b913..0fbcfa2f7233 100644 --- a/src/content/plugins/eval-source-map-dev-tool-plugin.mdx +++ b/src/content/plugins/eval-source-map-dev-tool-plugin.mdx @@ -19,6 +19,7 @@ related: This plugin enables more fine grained control of source map generation. It is also enabled automatically by certain settings of the [`devtool`](/configuration/devtool/) configuration option. ```js +import webpack from 'webpack'; new webpack.EvalSourceMapDevToolPlugin(options); ``` @@ -55,7 +56,9 @@ The following examples demonstrate some common use cases for this plugin. You can use the following code to replace the configuration option `devtool: eval-source-map` with an equivalent custom plugin configuration: ```js -module.exports = { +import webpack from 'webpack'; + +export default { // ... devtool: false, plugins: [new webpack.EvalSourceMapDevToolPlugin({})], @@ -67,6 +70,8 @@ module.exports = { The following code would exclude source maps for any modules in the `vendor.js` bundle: ```js +import webpack from 'webpack'; + new webpack.EvalSourceMapDevToolPlugin({ exclude: ['vendor.js'], }); diff --git a/src/content/plugins/html-webpack-plugin.mdx b/src/content/plugins/html-webpack-plugin.mdx index ff36be7f1b55..6f53403fd85c 100644 --- a/src/content/plugins/html-webpack-plugin.mdx +++ b/src/content/plugins/html-webpack-plugin.mdx @@ -23,10 +23,13 @@ bundles in the body using `script` tags. Add the plugin to your webpack configuration as follows: ```javascript -const HtmlWebpackPlugin = require('html-webpack-plugin'); -const path = require('path'); +import HtmlWebpackPlugin from 'html-webpack-plugin'; +import path from 'path'; +import { fileURLToPath } from 'url'; -module.exports = { +const __dirname = path.dirname(fileURLToPath(import.meta.url)); + +export default { entry: 'index.js', output: { path: path.resolve(__dirname, './dist'), diff --git a/src/content/plugins/limit-chunk-count-plugin.mdx b/src/content/plugins/limit-chunk-count-plugin.mdx index 0528f74cad92..0dbd2f9dbfea 100644 --- a/src/content/plugins/limit-chunk-count-plugin.mdx +++ b/src/content/plugins/limit-chunk-count-plugin.mdx @@ -13,6 +13,8 @@ contributors: While writing your code, you may have already added many code split points to load stuff on demand. After compiling you might notice that some chunks are too small - creating larger HTTP overhead. `LimitChunkCountPlugin` can post-process your chunks by merging them. ```js +import webpack from 'webpack'; + new webpack.optimize.LimitChunkCountPlugin({ // Options... }); @@ -31,8 +33,8 @@ Limit the maximum number of chunks using a value greater than or equal to `1`. U **webpack.config.js** ```javascript -const webpack = require('webpack'); -module.exports = { +import webpack from 'webpack'; +export default { // ... plugins: [ new webpack.optimize.LimitChunkCountPlugin({ diff --git a/src/content/plugins/module-concatenation-plugin.mdx b/src/content/plugins/module-concatenation-plugin.mdx index 4498c4224c86..35940bf388c0 100644 --- a/src/content/plugins/module-concatenation-plugin.mdx +++ b/src/content/plugins/module-concatenation-plugin.mdx @@ -12,6 +12,8 @@ In the past, one of webpack’s trade-offs when bundling was that each module in This plugin will enable the same concatenation behavior in webpack. By default this plugin is already enabled in [production `mode`](/configuration/mode/#mode-production) and disabled otherwise. If you need to override the production `mode` optimization, set the [`optimization.concatenateModules` option](/configuration/optimization/#optimizationconcatenatemodules) to `false`. To enable concatenation behavior in other modes, you can add `ModuleConcatenationPlugin` manually or use the `optimization.concatenateModules` option: ```js +import webpack from 'webpack'; + new webpack.optimize.ModuleConcatenationPlugin(); ``` @@ -87,7 +89,7 @@ function tryToAdd(group, module) { When using the webpack CLI, the `--stats-optimization-bailout` flag will display bailout reasons. When using the webpack config, add the following to the `stats` object: ```js -module.exports = { +export default { //... stats: { // Display bailout reasons diff --git a/src/content/plugins/module-federation-plugin.mdx b/src/content/plugins/module-federation-plugin.mdx index 08b2efa02a86..93f4b61d76f4 100644 --- a/src/content/plugins/module-federation-plugin.mdx +++ b/src/content/plugins/module-federation-plugin.mdx @@ -15,8 +15,10 @@ related: The `ModuleFederationPlugin` allows a build to provide or consume modules with other independent builds at runtime. ```ts -const { ModuleFederationPlugin } = require('webpack').container; -module.exports = { +import { container } from 'webpack'; +const { ModuleFederationPlugin } = container; + +export default { plugins: [ new ModuleFederationPlugin({ // options' typings in typescript @@ -40,8 +42,10 @@ Create a new runtime chunk with the specified name. **webpack.config.js** ```js -const { ModuleFederationPlugin } = require('webpack').container; -module.exports = { +import { container } from 'webpack'; +const { ModuleFederationPlugin } = container; + +export default { plugins: [ new ModuleFederationPlugin({ runtime: 'my-runtime-name', @@ -55,8 +59,10 @@ module.exports = { With the `shared` key in the configuration you can define libraries that are shared between your federated modules. The package name is the same as the one found in the `dependencies` section of your package.json. However, by default webpack will only share the root level of a library. ```js -const { ModuleFederationPlugin } = require('webpack').container; -module.exports = { +import { container } from 'webpack'; +const { ModuleFederationPlugin } = container; + +export default { plugins: [ new ModuleFederationPlugin({ // adds date-fns as shared module @@ -78,8 +84,10 @@ and webpack will automatically share `date-fns` between all your federated modul However, if you want to access something that is not located at the root level of the package, for example `date-fns/locale/en-GB/index.js`, you need to append `/` to the package name in your `shared` configuration: ```js -const { ModuleFederationPlugin } = require('webpack').container; -module.exports = { +import { container } from 'webpack'; +const { ModuleFederationPlugin } = container; + +export default { plugins: [ new ModuleFederationPlugin({ // adds date-fns as shared module @@ -101,8 +109,10 @@ There are three ways to specify the versions of shared libraries. This syntax allows you to share libraries with package name only. This approach is good for prototyping, but it will not allow you to scale to large production environment given that libraries like `react` and `react-dom` will require additional requirements. ```js -const { ModuleFederationPlugin } = require('webpack').container; -module.exports = { +import { container } from 'webpack'; +const { ModuleFederationPlugin } = container; + +export default { plugins: [ new ModuleFederationPlugin({ // adds lodash as shared module @@ -120,7 +130,10 @@ module.exports = { This syntax provides you more control over each shared library in which you can define package name as the key and version ([semver](https://semver.org/)) as the value. ```js -module.exports = { +import { container } from 'webpack'; +const { ModuleFederationPlugin } = container; + +export default { plugins: [ new ModuleFederationPlugin({ shared: { @@ -139,9 +152,10 @@ module.exports = { This syntax allows you to provide additional [hints](#sharing-hints) to each shared package where you define the package name as the key, and the value as an object containing hints to modify sharing behavior. ```js -const deps = require('./package.json').dependencies; +import pkg from './package.json' assert { type: 'json' }; +const deps = pkg.dependencies; -module.exports = { +export default { plugins: [ new ModuleFederationPlugin({ shared: { @@ -219,7 +233,10 @@ By default, webpack uses the version from the `package.json` file of the depende #### **Additional examples** ```js -module.exports = { +import { container } from 'webpack'; +const { ModuleFederationPlugin } = container; + +export default { plugins: [ new ModuleFederationPlugin({ // adds vue as shared module @@ -237,7 +254,10 @@ module.exports = { ``` ```js -module.exports = { +import { container } from 'webpack'; +const { ModuleFederationPlugin } = container; + +export default { plugins: [ new ModuleFederationPlugin({ // adds vue as shared module @@ -255,7 +275,10 @@ module.exports = { ``` ```js -module.exports = { +import { container } from 'webpack'; +const { ModuleFederationPlugin } = container; + +export default { plugins: [ new ModuleFederationPlugin({ // adds vue as shared module @@ -274,7 +297,10 @@ module.exports = { ``` ```js -module.exports = { +import { container } from 'webpack'; +const { ModuleFederationPlugin } = container; + +export default { plugins: [ new ModuleFederationPlugin({ shared: { diff --git a/src/content/plugins/normal-module-replacement-plugin.mdx b/src/content/plugins/normal-module-replacement-plugin.mdx index 84f15e9b4e18..1a1b047bde3d 100644 --- a/src/content/plugins/normal-module-replacement-plugin.mdx +++ b/src/content/plugins/normal-module-replacement-plugin.mdx @@ -14,15 +14,15 @@ The `NormalModuleReplacementPlugin` allows you to replace resources that match ` This can be useful for allowing different behaviour between builds. ```js +import webpack from 'webpack'; + new webpack.NormalModuleReplacementPlugin(resourceRegExp, newResource); ``` Note that the `resourceRegExp` is tested against the request you write in your code, not the resolved resource. For instance, `'./sum'` will be used to test instead of `'./sum.js'` when you have code `import sum from './sum'`. - Also please note that when using Windows, you have to accommodate the different folder separator symbol. E.g. `/src\/environments\/environment\.ts/` won't work on Windows, you have to use `/src[\\/]environments[\\/]environment\.ts/,` instead. - ## Basic Example Replace a specific module when building for a [development environment](/guides/production). @@ -32,6 +32,8 @@ Say you have a configuration file `some/path/config.development.module.js` and a Add the following plugin when building for production: ```javascript +import webpack from 'webpack'; + new webpack.NormalModuleReplacementPlugin( /some\/path\/config\.development\.js/, './config.production.js' @@ -45,7 +47,9 @@ Conditional build depending on an [specified environment](/configuration/configu Say you want a configuration with specific values for different build targets. ```javascript -module.exports = function (env) { +import webpack from 'webpack'; + +export default function (env) { var appTarget = env.APP_TARGET || 'VERSION_A'; return { plugins: [ @@ -63,7 +67,7 @@ module.exports = function (env) { }), ], }; -}; +} ``` Create the two configuration files: diff --git a/src/content/plugins/provide-plugin.mdx b/src/content/plugins/provide-plugin.mdx index d8f68281a4e2..c5e599ccc629 100644 --- a/src/content/plugins/provide-plugin.mdx +++ b/src/content/plugins/provide-plugin.mdx @@ -12,6 +12,8 @@ contributors: Automatically load modules instead of having to `import` or `require` them everywhere. ```js +import webpack from 'webpack'; + new webpack.ProvidePlugin({ identifier: 'module1', // ... @@ -21,6 +23,8 @@ new webpack.ProvidePlugin({ or ```js +import webpack from 'webpack'; + new webpack.ProvidePlugin({ identifier: ['module1', 'property1'], // ... @@ -32,7 +36,11 @@ By default, module resolution path is current folder (`./**)` and `node_modules` It is also possible to specify full path: ```js -const path = require('path'); +import path from 'path'; +import { fileURLToPath } from 'url'; +import webpack from 'webpack'; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); new webpack.ProvidePlugin({ identifier: path.resolve(path.join(__dirname, 'src/module1')), @@ -49,6 +57,8 @@ For importing the default export of an ES2015 module, you have to specify the de To automatically load `jquery` we can point both variables it exposes to the corresponding node module: ```javascript +import webpack from 'webpack'; + new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', @@ -69,6 +79,8 @@ jQuery('#item'); // <= also works Angular looks for `window.jQuery` in order to determine whether jQuery is present, see the [source code](https://github.com/angular/angular.js/blob/v1.5.9/src/Angular.js#L1821-L1823). ```javascript +import webpack from 'webpack'; + new webpack.ProvidePlugin({ 'window.jQuery': 'jquery', }); @@ -77,6 +89,8 @@ new webpack.ProvidePlugin({ ## Usage: Lodash Map ```javascript +import webpack from 'webpack'; + new webpack.ProvidePlugin({ _map: ['lodash', 'map'], }); @@ -85,6 +99,8 @@ new webpack.ProvidePlugin({ ### Usage: Vue.js ```javascript +import webpack from 'webpack'; + new webpack.ProvidePlugin({ Vue: ['vue/dist/vue.esm.js', 'default'], }); diff --git a/src/content/plugins/source-map-dev-tool-plugin.mdx b/src/content/plugins/source-map-dev-tool-plugin.mdx index 4dd3734ef771..a6208363a82a 100644 --- a/src/content/plugins/source-map-dev-tool-plugin.mdx +++ b/src/content/plugins/source-map-dev-tool-plugin.mdx @@ -17,6 +17,8 @@ related: This plugin enables more fine grained control of source map generation. It is also enabled automatically by certain settings of the [`devtool`](/configuration/devtool/) configuration option. ```js +import webpack from 'webpack'; + new webpack.SourceMapDevToolPlugin(options); ``` @@ -64,7 +66,9 @@ The following examples demonstrate some common use cases for this plugin. You can use the following code to replace the configuration option `devtool: inline-source-map` with an equivalent custom plugin configuration: ```js -module.exports = { +import webpack from 'webpack'; + +export default { // ... devtool: false, plugins: [new webpack.SourceMapDevToolPlugin({})], @@ -76,6 +80,8 @@ module.exports = { The following code would exclude source maps for any modules in the `vendor.js` bundle: ```js +import webpack from 'webpack'; + new webpack.SourceMapDevToolPlugin({ filename: '[file].map[query]', exclude: ['vendor.js'], @@ -87,6 +93,8 @@ new webpack.SourceMapDevToolPlugin({ Set a URL for source maps. Useful for hosting them on a host that requires authorization. ```js +import webpack from 'webpack'; + new webpack.SourceMapDevToolPlugin({ append: '\n//# sourceMappingURL=https://example.com/sourcemap/[url]', filename: '[file].map[query]', @@ -107,6 +115,8 @@ project With the following config: ```js +import webpack from 'webpack'; + new webpack.SourceMapDevToolPlugin({ filename: 'sourcemaps/[file].map', publicPath: 'https://example.com/project/', diff --git a/src/content/plugins/split-chunks-plugin.mdx b/src/content/plugins/split-chunks-plugin.mdx index b2dcbb647552..9c0b00774d66 100644 --- a/src/content/plugins/split-chunks-plugin.mdx +++ b/src/content/plugins/split-chunks-plugin.mdx @@ -58,7 +58,7 @@ This configuration object represents the default behavior of the `SplitChunksPlu **webpack.config.js** ```js -module.exports = { +export default { //... optimization: { splitChunks: { @@ -107,7 +107,7 @@ Note that it is applied to the fallback cache group as well (`splitChunks.fallba **webpack.config.js** ```js -module.exports = { +export default { //... optimization: { splitChunks: { @@ -121,7 +121,7 @@ module.exports = { Alternatively, you may provide a function for more control. The return value will indicate whether to include each chunk. ```js -module.exports = { +export default { //... optimization: { splitChunks: { @@ -137,7 +137,7 @@ module.exports = { If you are using webpack version 5.86.0 or later, you can also pass a regular expression: ```js -module.exports = { +export default { //... optimization: { splitChunks: { @@ -277,7 +277,9 @@ console.log(_.join(['Hello', 'webpack'], ' ')); **webpack.config.js** ```js -module.exports = { +import path from 'path'; + +export default { //... optimization: { splitChunks: { @@ -288,7 +290,7 @@ module.exports = { name(module, chunks, cacheGroupKey) { const moduleFileName = module .identifier() - .split('/') + .split(path.sep) .reduceRight((item) => item); const allChunksNames = chunks.map((item) => item.name).join('~'); return `${cacheGroupKey}-${allChunksNames}-${moduleFileName}`; @@ -321,7 +323,7 @@ Cache groups can inherit and/or override any options from `splitChunks.*`; but ` **webpack.config.js** ```js -module.exports = { +export default { //... optimization: { splitChunks: { @@ -348,7 +350,7 @@ If the current chunk contains modules already split out from the main bundle, it **webpack.config.js** ```js -module.exports = { +export default { //... optimization: { splitChunks: { @@ -371,7 +373,7 @@ Allows to assign modules to a cache group by module type. **webpack.config.js** ```js -module.exports = { +export default { //... optimization: { splitChunks: { @@ -398,7 +400,9 @@ Providing a function to`{cacheGroup}.test`: **webpack.config.js** ```js -module.exports = { +import path from 'path'; + +export default { //... optimization: { splitChunks: { @@ -407,7 +411,7 @@ module.exports = { test(module) { // `module.resource` contains the absolute path of the file on disk. // Note the usage of `path.sep` instead of / or \, for cross-platform compatibility. - const path = require('path'); + return ( module.resource && module.resource.endsWith('.svg') && @@ -433,7 +437,7 @@ Providing a `RegExp` to `{cacheGroup}.test`: **webpack.config.js** ```js -module.exports = { +export default { //... optimization: { splitChunks: { @@ -460,7 +464,7 @@ W> This option can also be set globally in `splitChunks.filename`, but this isn' **webpack.config.js** ```js -module.exports = { +export default { //... optimization: { splitChunks: { @@ -479,7 +483,7 @@ And as a function: **webpack.config.js** ```js -module.exports = { +export default { //... optimization: { splitChunks: { @@ -501,7 +505,7 @@ It is possible to create a folder structure by providing path prefixing the file **webpack.config.js** ```js -module.exports = { +export default { //... optimization: { splitChunks: { @@ -524,7 +528,7 @@ Tells webpack to ignore [`splitChunks.minSize`](#splitchunksminsize), [`splitChu **webpack.config.js** ```js -module.exports = { +export default { //... optimization: { splitChunks: { @@ -547,7 +551,7 @@ Sets the hint for chunk id. It will be added to chunk's filename. **webpack.config.js** ```js -module.exports = { +export default { //... optimization: { splitChunks: { @@ -632,7 +636,7 @@ Create a `commons` chunk, which includes all code shared between entry points. **webpack.config.js** ```js -module.exports = { +export default { //... optimization: { splitChunks: { @@ -657,7 +661,7 @@ Create a `vendors` chunk, which includes all code from `node_modules` in the who **webpack.config.js** ```js -module.exports = { +export default { //... optimization: { splitChunks: { @@ -682,7 +686,7 @@ Create a `custom vendor` chunk, which contains certain `node_modules` packages m **webpack.config.js** ```js -module.exports = { +export default { //... optimization: { splitChunks: { diff --git a/src/content/plugins/virtual-url-plugin.mdx b/src/content/plugins/virtual-url-plugin.mdx index 0c1a6752830a..c8425ee8bd2c 100644 --- a/src/content/plugins/virtual-url-plugin.mdx +++ b/src/content/plugins/virtual-url-plugin.mdx @@ -10,7 +10,7 @@ Allow creating virtual modules of any type, such as `.ts`, `.json`, `.css`, etc. ```javascript -const webpack = require('webpack'); +import webpack from 'webpack'; new webpack.experiments.schemes.VirtualUrlPlugin({ myModule: `export const msg = "from virtual module"`, @@ -53,7 +53,7 @@ console.log('App version: ', buildTime); Use custom schema ```javascript -const webpack = require('webpack'); +import webpack from 'webpack'; new webpack.experiments.schemes.VirtualUrlPlugin( { @@ -76,7 +76,7 @@ console.log(msg); Create multiple virtual modules of different types ```javascript -const webpack = require('webpack'); +import webpack from 'webpack'; new webpack.experiments.schemes.VirtualUrlPlugin({ myCssModule: { @@ -100,8 +100,12 @@ import 'virtual:myCssModule'; Virtualize the routing file ```javascript -const webpack = require('webpack'); -const path = require('path'); +import webpack from 'webpack'; +import fs from 'fs'; +import path from 'path'; +import { fileURLToPath } from 'url'; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); const watchDir = path.join(__dirname, './src/routes'); new webpack.experiments.schemes.VirtualUrlPlugin({ diff --git a/src/styles/partials/_vars.scss b/src/styles/partials/_vars.scss index 289f25568fd2..8a7e90d2023e 100644 --- a/src/styles/partials/_vars.scss +++ b/src/styles/partials/_vars.scss @@ -18,11 +18,18 @@ $screens: ( medium: 768px, ); -$font-stack-body: 'Source Sans Pro', -apple-system, BlinkMacSystemFont, - 'Segoe UI', Helvetica, Arial, sans-serif; -$font-stack-heading: 'Source Serif Pro', ui-serif, Georgia, Cambria, - 'Times New Roman', Times, serif; -$font-stack-code: 'Source Code Pro', Consolas, 'Liberation Mono', Menlo, Courier, - monospace; +$font-stack-body: + 'Source Sans Pro', + -apple-system, + BlinkMacSystemFont, + 'Segoe UI', + Helvetica, + Arial, + sans-serif; +$font-stack-heading: + 'Source Serif Pro', ui-serif, Georgia, Cambria, 'Times New Roman', Times, + serif; +$font-stack-code: + 'Source Code Pro', Consolas, 'Liberation Mono', Menlo, Courier, monospace; $text-color-highlight: lighten(map-get($colors, denim), 5%); From edfae50e5ead4df272e0ac7f9dd957a16e8ab54e Mon Sep 17 00:00:00 2001 From: Deeksha Varshney Date: Sun, 14 Dec 2025 00:12:01 +0530 Subject: [PATCH 5/8] fix(server): Access MDX default export to resolve 'Node/Mode is not defined' --- src/server.jsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/server.jsx b/src/server.jsx index 2bfc1e67b54f..5ec9163b840e 100644 --- a/src/server.jsx +++ b/src/server.jsx @@ -26,7 +26,7 @@ export default (locals) => { require(`./content/${path}`)} + import={(path) => require(`./content/${path}`).default} /> {isPrintPage(locals.path) ? ( From 32434357acee5f766a549f8be5f018a5b355ad77 Mon Sep 17 00:00:00 2001 From: Deeksha Varshney Date: Sun, 14 Dec 2025 00:31:06 +0530 Subject: [PATCH 6/8] fix(mdx): Map missing custom MDX components (Mode, Node, W, I) to resolve SSR ReferenceError --- src/mdx-components.js | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/mdx-components.js b/src/mdx-components.js index c6a120cec2d3..b13aa54e6a93 100644 --- a/src/mdx-components.js +++ b/src/mdx-components.js @@ -2,6 +2,7 @@ import Badge from './components/Badge/Badge'; import LinkComponent from './components/mdxComponents/Link'; import StackBlitzPreview from './components/StackBlitzPreview/StackBlitzPreview'; import CodeBlockWithCopy from './components/CodeBlockWithCopy/CodeBlockWithCopy'; +import { Mode, Node, W, I } from './components/Configuration/components'; /** @returns {import('mdx/types.js').MDXComponents} */ export function useMDXComponents() { @@ -10,5 +11,9 @@ export function useMDXComponents() { Badge: Badge, StackBlitzPreview: StackBlitzPreview, pre: CodeBlockWithCopy, + Mode: Mode, + Node: Node, + W: W, + I: I, }; } From f6c8ade1b792687fa5375dfa62f856f86635dd8e Mon Sep 17 00:00:00 2001 From: Deeksha Varshney Date: Sun, 14 Dec 2025 00:49:31 +0530 Subject: [PATCH 7/8] fix(mdx): Use import * as to resolve configuration component ReferenceError in SSR --- src/mdx-components.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/mdx-components.js b/src/mdx-components.js index b13aa54e6a93..9235932d020b 100644 --- a/src/mdx-components.js +++ b/src/mdx-components.js @@ -2,7 +2,7 @@ import Badge from './components/Badge/Badge'; import LinkComponent from './components/mdxComponents/Link'; import StackBlitzPreview from './components/StackBlitzPreview/StackBlitzPreview'; import CodeBlockWithCopy from './components/CodeBlockWithCopy/CodeBlockWithCopy'; -import { Mode, Node, W, I } from './components/Configuration/components'; +import * as ConfigComponents from './components/Configuration/components'; /** @returns {import('mdx/types.js').MDXComponents} */ export function useMDXComponents() { @@ -11,9 +11,9 @@ export function useMDXComponents() { Badge: Badge, StackBlitzPreview: StackBlitzPreview, pre: CodeBlockWithCopy, - Mode: Mode, - Node: Node, - W: W, - I: I, + Mode: ConfigComponents.Mode, + Node: ConfigComponents.Node, + W: ConfigComponents.W, + I: ConfigComponents.I, }; } From 085a47e7ae799c2c4d4a5dd863b26f9f72a1bf70 Mon Sep 17 00:00:00 2001 From: Deeksha Varshney Date: Sun, 14 Dec 2025 01:05:15 +0530 Subject: [PATCH 8/8] fix(mdx): Remove missing config component imports to resolve ReferenceError --- src/mdx-components.js | 5 ----- src/server.jsx | 2 +- 2 files changed, 1 insertion(+), 6 deletions(-) diff --git a/src/mdx-components.js b/src/mdx-components.js index 9235932d020b..c6a120cec2d3 100644 --- a/src/mdx-components.js +++ b/src/mdx-components.js @@ -2,7 +2,6 @@ import Badge from './components/Badge/Badge'; import LinkComponent from './components/mdxComponents/Link'; import StackBlitzPreview from './components/StackBlitzPreview/StackBlitzPreview'; import CodeBlockWithCopy from './components/CodeBlockWithCopy/CodeBlockWithCopy'; -import * as ConfigComponents from './components/Configuration/components'; /** @returns {import('mdx/types.js').MDXComponents} */ export function useMDXComponents() { @@ -11,9 +10,5 @@ export function useMDXComponents() { Badge: Badge, StackBlitzPreview: StackBlitzPreview, pre: CodeBlockWithCopy, - Mode: ConfigComponents.Mode, - Node: ConfigComponents.Node, - W: ConfigComponents.W, - I: ConfigComponents.I, }; } diff --git a/src/server.jsx b/src/server.jsx index 5ec9163b840e..2bfc1e67b54f 100644 --- a/src/server.jsx +++ b/src/server.jsx @@ -26,7 +26,7 @@ export default (locals) => { require(`./content/${path}`).default} + import={(path) => require(`./content/${path}`)} /> {isPrintPage(locals.path) ? (