diff --git a/src/content/api/cli.mdx b/src/content/api/cli.mdx index c60d0d03ffa5..614695a5db36 100644 --- a/src/content/api/cli.mdx +++ b/src/content/api/cli.mdx @@ -49,7 +49,7 @@ webpack-cli offers a variety of commands to make working with webpack easier. By | [`help`](#help) | `help\|h [command] [option]` | Display help for commands and options. | | [`info`](#info) | `info\|i [options]` | Outputs information about your system. | | [`serve`](#serve) | `serve\|server\|s [options]` | Run the `webpack-dev-server`. | -| [`version`](#version) | `version\|v [commands...]` | Output the version number of 'webpack', 'webpack-cli' and 'webpack-dev-server' and other packages. | +| [`version`](#version) | `version\|v [options]` | Output the version number of 'webpack', 'webpack-cli' and 'webpack-dev-server' and other packages. | | [`watch`](#watch) | `watch\|w [entries...] [options]` | Run webpack and watch for files changes. | ### Build @@ -176,7 +176,7 @@ npx webpack info [options] **example** ```bash -npx webpack info --output json --addition-package postcss +npx webpack info --output json --additional-package postcss ``` #### Options for info @@ -621,11 +621,11 @@ npx webpack --config-node-env production # process.env.NODE_ENV = 'production' When the `mode` option is not specified in the configuration, you can use the `--config-node-env` option to set the `mode`. For example, using `--config-node-env production` will set both `process.env.NODE_ENV` and `mode` to `'production'`. -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. +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.configNodeEnv` within the function and can be used accordingly. ```js export default (env, argv) => { - console.log(argv.defineProcessEnvNodeEnv); // 'production' if --config-node-env production is used + console.log(argv.configNodeEnv); // 'production' if --config-node-env production is used return { // your configuration }; diff --git a/src/content/api/compilation-hooks.mdx b/src/content/api/compilation-hooks.mdx index 19083338efc1..c961b3d99ccc 100644 --- a/src/content/api/compilation-hooks.mdx +++ b/src/content/api/compilation-hooks.mdx @@ -21,7 +21,7 @@ compilation of all the modules in the dependency graph of an application. During the compilation phase, modules are loaded, sealed, optimized, chunked, hashed and restored. -The `Compilation` class also extends `Tapable` and provides the following +The `Compilation` class also exposes a `hooks` object of tapable hooks and provides the following lifecycle hooks. They can be tapped the same way as compiler hooks: ```js @@ -84,7 +84,7 @@ Called when all modules have been built without errors. ## finishRebuildingModule -`SyncHook` +`AsyncSeriesHook` Executed when a module has been rebuilt, in case of both success or with errors. @@ -159,7 +159,7 @@ Called after modules optimization has completed. Called at the beginning of the chunk optimization phase. A plugin can tap into this hook to perform optimizations on chunks. -- Callback Parameters: `chunks` +- Callback Parameters: `chunks` `chunkGroups` ## afterOptimizeChunks @@ -167,7 +167,7 @@ Called at the beginning of the chunk optimization phase. A plugin can tap into t Fired after chunk optimization has completed. -- Callback Parameters: `chunks` +- Callback Parameters: `chunks` `chunkGroups` ## optimizeTree @@ -187,7 +187,7 @@ Called after the dependency tree optimization has completed with success. ## optimizeChunkModules -`SyncBailHook` +`AsyncSeriesBailHook` Called after the tree optimization, at the beginning of the chunk modules optimization. A plugin can tap into this hook to perform optimizations of chunk modules. @@ -205,7 +205,7 @@ Called after the chunkmodules optimization has completed successfully. `SyncBailHook` -Called to determine whether or not to store records. Returning anything `!== false` will prevent every other "record" hook from being executed ([`record`](#record), [`recordModules`](#recordmodules), [`recordChunks`](#recordchunks) and [`recordHash`](#recordhash)). +Called to determine whether or not to store records. Returning `false` prevents the "record" hooks from being executed ([`record`](#record), [`recordModules`](#recordmodules), [`recordChunks`](#recordchunks) and [`recordHash`](#recordhash)); any other value allows them. ## reviveModules @@ -347,7 +347,7 @@ Called before modules are hashed. ## afterModuleHash -`syncHook` +`SyncHook` Called after modules are hashed. @@ -638,7 +638,9 @@ Executed right after `needAdditionalSeal`. Triggered to emit the hash for each chunk. -- Callback Parameters: `chunk` `chunkHash` +- Callback Parameters: `chunk` `chunkHash` `context` + +`context` is a `ChunkHashContext` holding `chunkGraph`, `moduleGraph`, `runtimeTemplate` and `codeGenerationResults`. ## moduleAsset @@ -662,7 +664,7 @@ Triggered when an asset from a chunk was added to the compilation. Called to determine the path of an asset. -- Callback Parameters: `path` `options` +- Callback Parameters: `path` `options` `assetInfo` ## needAdditionalPass @@ -678,6 +680,14 @@ Executed after setting up a child compiler. - Callback Parameters: `childCompiler` `compilerName` `compilerIndex` +## log + +`SyncBailHook` + +Allows to log into [stats](/configuration/stats/) when enabled, see [`stats.logging`, `stats.loggingDebug` and `stats.loggingTrace` options](/configuration/infrastructureLogging/). + +- Callback Parameters: `origin`, `logEntry` + ## normalModuleLoader Since webpack v5 `normalModuleLoader` hook was removed. Now to access the loader use `NormalModule.getCompilationHooks(compilation).loader` instead. diff --git a/src/content/api/compilation-object.mdx b/src/content/api/compilation-object.mdx index e2b8e2ab0112..264dc43036a7 100644 --- a/src/content/api/compilation-object.mdx +++ b/src/content/api/compilation-object.mdx @@ -42,26 +42,24 @@ Parameters: ### findModule -`function (module)` +`function (identifier)` -Attempts to search for a module by its identifier. +Attempts to search for a module by its identifier. Returns the module, or `undefined` if none matches. Parameters: -- `module` - module to be searched for. The identifier is extracted from the module by the compilation using `module.identifier()` method. +- `identifier` - the identifier string of the module to be searched for. ### buildModule -`function (module, optional, origin, dependencies)` +`function (module, callback)` Builds the given module. Parameters: - `module` - the module to be built. -- `optional` - optional flag. -- `origin` - origin module from which this module build was requested. -- `dependencies` - optional dependencies of the module to be built. +- `callback` - invoked as `callback(err, module)` when the build finishes. ### processModuleDependencies @@ -124,10 +122,6 @@ Parameters: Unseals the compilation. -Parameters: - -- `callback` - function to be invoked when the compilation has been unsealed. - ### reportDependencyErrorsAndWarnings `function (module, blocks)` @@ -172,26 +166,16 @@ Parameters: - `module` - the module to assign depth to. -### getDependencyReference - -`function (module, dependency)` - -Returns the reference to the dependency from a given module. - -Parameters: - -- `module` - the module at question. -- `dependency` - the dependency to get reference to. - -### processDependenciesBlocksForChunkGroups +### getDependencyReferencedExports -`function (inputChunkGroups)` +`function (dependency, runtime)` -Creates the `Chunk` graph from the `Module` graph. The process is done in two phases. Phase one: traverse the module graph and build a basic chunks graph in `chunkDependencies`. Phase two: traverse every possible way through the basic chunk graph and track the available modules. While traversing, `processDependenciesBlocksForChunkGroups` connects chunks with each other and `Blocks` with `Chunks`. It stops traversing when all modules for a chunk are already available and it doesn't connect unneeded chunks. +Returns the exports referenced by the given dependency. Parameters: -- `inputChunkGroups` - chunk groups that are processed. +- `dependency` - the dependency to get the referenced exports of. +- `runtime` - the runtime to get them for. ### removeReasonsOfDependencyBlock diff --git a/src/content/api/compiler-hooks.mdx b/src/content/api/compiler-hooks.mdx index d0ecb8d09794..f361d06d0151 100644 --- a/src/content/api/compiler-hooks.mdx +++ b/src/content/api/compiler-hooks.mdx @@ -14,8 +14,8 @@ contributors: --- The `Compiler` module is the main engine that creates a compilation instance -with all the options passed through the [CLI](/api/cli) or [Node API](/api/node). It extends the -`Tapable` class in order to register and call plugins. Most user-facing plugins +with all the options passed through the [CLI](/api/cli) or [Node API](/api/node). It exposes a +`hooks` object of [tapable](https://github.com/webpack/tapable) hooks (`SyncHook`, `AsyncSeriesHook`, …) used to register plugins. Most user-facing plugins are first registered on the `Compiler`. When developing a plugin for webpack, you might want to know where each hook is called. To learn this, search for `hooks..call` across the webpack source. @@ -323,11 +323,3 @@ Called when the compiler is closing. Allows to use infrastructure logging when enabled in the configuration via [`infrastructureLogging` option](/configuration/infrastructureLogging/). - Callback Parameters: `name`, `type`, `args` - -### log - -`SyncBailHook` - -Allows to log into [stats](/configuration/stats/) when enabled, see [`stats.logging`, `stats.loggingDebug` and `stats.loggingTrace` options](/configuration/infrastructureLogging/). - -- Callback Parameters: `origin`, `logEntry` diff --git a/src/content/api/contextmodulefactory-hooks.mdx b/src/content/api/contextmodulefactory-hooks.mdx index f455fae9071c..50f814b2f87c 100644 --- a/src/content/api/contextmodulefactory-hooks.mdx +++ b/src/content/api/contextmodulefactory-hooks.mdx @@ -8,7 +8,7 @@ contributors: The `ContextModuleFactory` module is used by the `Compiler` to generate dependencies from webpack specific [require.context](/api/module-methods/#requirecontext) API. It resolves the requested directory, generates requests for each file and filters against passed regExp. Matching dependencies then passes through [NormalModuleFactory](/api/normalmodulefactory-hooks). -The `ContextModuleFactory` class extends `Tapable` and provides the following +The `ContextModuleFactory` class exposes a `hooks` object of tapable hooks and provides the following lifecycle hooks. They can be tapped the same way as compiler hooks: ```js @@ -46,6 +46,6 @@ Called after directory contents are read. On recursive mode, calls for each sub- `AsyncSeriesWaterfallHook` -Called for each file after the request is created but before filtering against regExp. +Called once per directory with the array of generated `{ context, request }` alternatives, before filtering against regExp. Return the (possibly modified) array. -- Callback Parameters: `request` `options` +- Callback Parameters: `modules` `options` diff --git a/src/content/api/hot-module-replacement.mdx b/src/content/api/hot-module-replacement.mdx index e83e396b4820..904f412d302d 100644 --- a/src/content/api/hot-module-replacement.mdx +++ b/src/content/api/hot-module-replacement.mdx @@ -327,10 +327,10 @@ The `info` parameter will be an object containing some of the following values: { type: 'self-declined' | 'declined' | 'unaccepted' | 'accepted' | - 'disposed' | 'accept-errored' | + 'disposed' | 'accept-errored' | 'accept-error-handler-errored' | 'self-accept-errored' | 'self-accept-error-handler-errored', moduleId: 4, // The module in question. - dependencyId: 3, // For errors: the module id owning the accept handler. + dependencyId: 3, // For errors: the id of the updated dependency whose accept handler threw (`moduleId` is the module owning the handler). chain: [1, 2, 3, 4], // For declined/accepted/unaccepted: the chain from where the update was propagated. parentId: 5, // For declined: the module id of the declining parent outdatedModules: [1, 2, 3, 4], // For accepted: the modules that are outdated and will be disposed @@ -338,8 +338,8 @@ The `info` parameter will be an object containing some of the following values: 5: [4] }, error: new Error(...), // For errors: the thrown error - originalError: new Error(...) // For self-accept-error-handler-errored: - // the error thrown by the module before the error handler tried to handle it. + originalError: new Error(...) // For accept-error-handler-errored and self-accept-error-handler-errored: + // the error thrown by the accept handler or the module before the error handler tried to handle it. } ``` diff --git a/src/content/api/loaders.mdx b/src/content/api/loaders.mdx index d3572e748537..936ef8a47068 100644 --- a/src/content/api/loaders.mdx +++ b/src/content/api/loaders.mdx @@ -264,7 +264,7 @@ this.callback( 1. The first argument must be an `Error` or `null` 2. The second argument is a `string` or a [`Buffer`](https://nodejs.org/api/buffer.html). 3. Optional: The third argument must be a source map that is parsable by [this module](https://github.com/mozilla/source-map). -4. Optional: The fourth option, ignored by webpack, can be anything (e.g. some metadata). +4. Optional: The fourth argument (`meta`) can be anything (e.g. some metadata). webpack only reads `meta.webpackAST` and uses it as the pre-parsed AST; everything else is passed on to the next loader. T> It can be useful to pass an abstract syntax tree (AST), like [`ESTree`](https://github.com/estree/estree), as the fourth argument (`meta`) to speed up the build time if you want to share common ASTs between loaders. @@ -308,10 +308,10 @@ T> Unlike throwing an Error directly, it will NOT interrupt the compilation proc ### this.emitFile ```ts -emitFile(name: string, content: Buffer|string, sourceMap: {...}) +emitFile(name: string, content: Buffer|string, sourceMap: {...}, assetInfo?: AssetInfo) ``` -Emit a file. This is webpack-specific. +Emit a file. This is webpack-specific. The optional `assetInfo` is stored as the asset's info in `buildInfo.assetsInfo`. ### this.emitWarning @@ -443,6 +443,7 @@ An alternative lightweight solution for the child compiler to compile and execut - `request`: the request string to load the module from - `options`: + - `baseUri`: the base URI used for the built modules - `layer`: specify a layer in which this module is placed/compiled - `publicPath`: the public path used for the built modules - `callback`: an optional Node.js style callback returning the exports of the module or a namespace object for ESM. `importModule` will return a Promise if no callback is provided. @@ -525,7 +526,21 @@ Resolves the given request to a module, applies all configured loaders and calls An array of all the loaders. It is writable in the pitch phase. ```ts -loaders = [{request: string, path: string, query: string, module: function}] +loaders = [{ + request: string, + path: string, + query: string, + fragment: string, + options: object | string | undefined, + ident: string, + normal: function | undefined, + pitch: function | undefined, + raw: boolean | undefined, + data: object | undefined, + pitchExecuted: boolean, + normalExecuted: boolean, + type?: 'commonjs' | 'module' +}] ``` In [the example](#example-for-the-loader-context): @@ -536,13 +551,13 @@ In [the example](#example-for-the-loader-context): request: "/abc/loader1.js?xyz", path: "/abc/loader1.js", query: "?xyz", - module: [Function], + normal: [Function], }, { request: "/abc/node_modules/loader2/index.js", path: "/abc/node_modules/loader2/index.js", query: "", - module: [Function], + normal: [Function], }, ]; ``` @@ -671,19 +686,11 @@ W> The usage of these properties is highly discouraged since we are planning to ### this.debug -A boolean flag. It is set when in debug mode. - -### this.inputValue - -Passed from the last loader. If you would execute the input argument as a module, consider reading this variable for a shortcut (for performance). +No longer set by webpack. It is only set when `LoaderOptionsPlugin` is configured with a `debug` option, which copies the option onto the loader context. ### this.minimize -Tells if result should be minimized. - -### this.value - -Pass values to the next loader. If you know what your result exports if executed as a module, set this value here (as an only element array). +No longer set by webpack. It is only set when `LoaderOptionsPlugin` is configured with a `minimize` option, which copies the option onto the loader context. ### this.\_module diff --git a/src/content/api/module-methods.mdx b/src/content/api/module-methods.mdx index 61e258f7b989..24fa26055a3d 100644 --- a/src/content/api/module-methods.mdx +++ b/src/content/api/module-methods.mdx @@ -360,7 +360,7 @@ define([name: String], [dependencies: String[]], factoryMethod: function(...)) If `dependencies` are provided, `factoryMethod` will be called with the exports of each dependency (in the same order). If `dependencies` are not provided, `factoryMethod` is called with `require`, `exports` and `module` (for compatibility!). If this function returns a value, this value is exported by the module. The compiler ensures that each dependency is available. -W> Note that webpack ignores the `name` argument. +W> The `name` argument does not affect the module id. webpack registers it as a local module, so other `define` or `require` calls in the same file can reference it. ```js define(["jquery", "my-module"], ($, myModule) => @@ -410,44 +410,6 @@ import("b").then((b) => { W> There is no option to provide a chunk name. -## Labeled Modules - -W> These syntaxes are legacy. We highly recommend using ES6 Modules for modern applications. - -The internal `LabeledModulesPlugin` enables you to use the following methods for exporting and requiring within your modules: - -### export label - -Export the given `value`. The label can occur before a function declaration or a variable declaration. The function name or variable name is the identifier under which the value is exported. - -```ts -export: const answer = 42; -export: function method(value) { - // Do something... -}; -``` - -W> Using it in an async function may not have the expected effect. - -### require label - -Make all exports from the dependency available in the current scope. The `require` label can occur before a string. The dependency must export values with the `export` label. CommonJS or AMD modules cannot be consumed. - -**some-dependency.js** - -```ts -export: const answer = 42; -export: function method(value) { - // Do something... -}; -``` - -```ts -require: 'some-dependency'; -console.log(answer); -method(...); -``` - ## Webpack Aside from the module syntaxes described above, webpack also allows a few custom, webpack-specific methods: @@ -494,6 +456,8 @@ The full list of available modes and their behavior is described in [`import()`] require.include((dependency: String)); ``` +W> `require.include()` emits a `RequireIncludeDeprecationWarning` ("require.include() is deprecated and will be removed soon.") by default. Set [`module.parser.javascript.requireInclude`](/configuration/module/#moduleparserjavascript) to `true` to silence it, or to `false` to disable the feature. + Include a `dependency` without executing it. This can be used for optimizing the position of a module in the output chunks. ```js diff --git a/src/content/api/module-variables.mdx b/src/content/api/module-variables.mdx index 551de210ad85..7bf9e8a96edb 100644 --- a/src/content/api/module-variables.mdx +++ b/src/content/api/module-variables.mdx @@ -73,11 +73,16 @@ For compatibility reasons webpack polyfills the `global` variable by default. ## \_\_dirname (NodeJS) -Depending on the configuration option `node.__dirname`: +Depending on the configuration option [`node.__dirname`](/configuration/node/): - `false`: Not defined -- `mock`: equal to `'/'` -- `true`: [node.js \_\_dirname](https://nodejs.org/api/globals.html#globals_dirname) +- `true`: The directory of the module, relative to the compiler [`context`](/configuration/entry-context/#context) +- `'mock'`: equal to `'/'` +- `'warn-mock'`: equal to `'/'`, with a warning +- `'node-module'`: Derived from `import.meta.url` (or `import.meta.dirname` where supported) in ES module output +- `'eval-only'`: Left for Node.js to evaluate at runtime + +Defaults to `'eval-only'` for Node.js-like targets and `'mock'` otherwise. If used inside an expression that is parsed by the Parser, the configuration option is treated as `true`. @@ -85,13 +90,11 @@ If used inside an expression that is parsed by the Parser, the configuration opt The `import.meta` exposes context-specific metadata to a JavaScript module, such as the URL of the module. It is only available in [ESM](/guides/ecma-script-modules/). -Please note that webpack does not support direct access to `import.meta`. Instead, you should access its properties or use destructuring assignment. E.g., +Direct access to `import.meta` is supported: webpack replaces it with an object of the known properties (`url`, `webpack`, `main`, `env`, …). Unknown properties are `undefined` unless [`module.parser.javascript.importMeta`](/configuration/module/#moduleparserjavascriptimportmeta) is set to `'preserve-unknown'` or an object. ```js -// webpack will warn about this -Object.keys(import.meta); +Object.keys(import.meta); // e.g. ['url', 'webpack', 'main', 'env'] -// fine to use console.log(import.meta.url); const { url } = import.meta; ``` @@ -302,11 +305,16 @@ const icons = import.meta.glob("./icons/*.svg", { ## \_\_filename (NodeJS) -Depending on the configuration option `node.__filename`: +Depending on the configuration option [`node.__filename`](/configuration/node/): - `false`: Not defined -- `mock`: equal to `'/index.js'` -- `true`: [node.js \_\_filename](https://nodejs.org/api/globals.html#globals_filename) +- `true`: The path of the module, relative to the compiler [`context`](/configuration/entry-context/#context) +- `'mock'`: equal to `'/index.js'` +- `'warn-mock'`: equal to `'/index.js'`, with a warning +- `'node-module'`: Derived from `import.meta.url` (or `import.meta.filename` where supported) in ES module output +- `'eval-only'`: Left for Node.js to evaluate at runtime + +Defaults to `'eval-only'` for Node.js-like targets and `'mock'` otherwise. If used inside an expression that is parsed by the Parser, the configuration option is treated as `true`. @@ -497,7 +505,3 @@ This is a webpack specific feature and it's available since webpack 5.25.0. ```js console.log(__webpack_runtime_id__ === "main"); ``` - -## DEBUG (webpack-specific) - -Equals the configuration option `debug`. diff --git a/src/content/api/node.mdx b/src/content/api/node.mdx index b0c09b3178b1..62f9ef0d6d6f 100644 --- a/src/content/api/node.mdx +++ b/src/content/api/node.mdx @@ -164,7 +164,7 @@ watching.close((closeErr) => { ``` W> It’s not allowed to watch or run again before the existing watcher has been -closed or invalidated. +closed. ### Invalidate `Watching` @@ -285,23 +285,23 @@ webpack( ); ``` -W> Multiple configurations will **not be run in parallel**. Each -configuration is only processed after the previous one has finished -processing. +W> Multiple configurations are **run in parallel** by default +(`parallelism: Infinity`). Use the [`parallelism`](/configuration/configuration-types/#parallelism) option on the +configuration array or [`dependencies`](/configuration/configuration-types/#dependencies) in a configuration to limit or order them. ### MultiCompiler hooks A `MultiCompiler` exposes the child compilers' hooks as one, so a plugin can tap the set instead of every child: -| Hook | Type | Description | -| ------------------- | --------------------------------------- | -------------------------------------------------------------------------------- | -| `done` | `SyncHook<[MultiStats, Compiler[]]>` | Called once every child compilation has finished. Aggregated, not a `MultiHook`. | -| `shutdown` | `AsyncSeriesHook<[Compiler]>` | Called when the compilers are closing, once per child. | -| `invalid` | `SyncHook<[string \| null, number]>` | Called when a watched file changes in any of the children. | -| `run` | `AsyncSeriesHook<[Compiler]>` | Called before a child starts a non-watch build. | -| `watchRun` | `AsyncSeriesHook<[Compiler]>` | Called before a child starts a watch build. | -| `watchClose` | `SyncHook<[]>` | Called when watching stops. | -| `infrastructureLog` | `SyncBailHook<[string, string, any[]]>` | Infrastructure logging for any child. | +| Hook | Type | Description | +| ------------------- | --------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | +| `done` | `SyncHook<[MultiStats, Compiler[]]>` | Called once every child compilation has finished. Aggregated, not a `MultiHook`. | +| `shutdown` | `AsyncSeriesHook<[]>` | Called when the compilers are closing. A `MultiHook` over the children's `shutdown` hooks; taps receive no arguments. | +| `invalid` | `SyncHook<[string \| null, number]>` | Called when a watched file changes in any of the children. | +| `run` | `AsyncSeriesHook<[Compiler]>` | Called before a child starts a non-watch build. | +| `watchRun` | `AsyncSeriesHook<[Compiler]>` | Called before a child starts a watch build. | +| `watchClose` | `SyncHook<[]>` | Called when watching stops. | +| `infrastructureLog` | `SyncBailHook<[string, string, any[]]>` | Infrastructure logging for any child. | Since webpack 5.110.0 the `done` hook is also handed the compilers whose build actually ran, in configuration order. In watch mode a change usually invalidates only some of the children, and the others are reported from their previous stats, so this is how a plugin tells what is new: @@ -394,5 +394,5 @@ and many other packages, uses to mysteriously hide your files but continue serving them up to the browser! T> The output file system you provide needs to be compatible with Node’s own -[`fs`](https://nodejs.org/api/fs.html) interface, which requires the `mkdirp` -and `join` helper methods. +[`fs`](https://nodejs.org/api/fs.html) interface: it must provide `mkdir`, +`writeFile`, `stat` and `readFile`; `join`, `relative` and `dirname` are optional. diff --git a/src/content/api/normalmodulefactory-hooks.mdx b/src/content/api/normalmodulefactory-hooks.mdx index d66e64d69abe..a41874863b58 100644 --- a/src/content/api/normalmodulefactory-hooks.mdx +++ b/src/content/api/normalmodulefactory-hooks.mdx @@ -9,7 +9,7 @@ contributors: The `NormalModuleFactory` module is used by the `Compiler` to generate modules. Starting with entry points, it resolves each request, parses the content to find further requests, and keeps crawling through files by resolving all and parsing any new files. At last stage, each dependency becomes a Module instance. -The `NormalModuleFactory` class extends `Tapable` and provides the following +The `NormalModuleFactory` class exposes a `hooks` object of tapable hooks and provides the following lifecycle hooks. They can be tapped the same way as compiler hooks: ```js @@ -58,11 +58,13 @@ Called before the request is resolved. A dependency can be ignored by returning ## resolveForScheme -`AsyncSeriesBailHook` +`HookMap` Called before a request with scheme (URI) is resolved. -- Callback Parameters: `resolveData` +- Hook Parameters: `scheme` + +- Callback Parameters: `resourceData` `resolveData` ## afterResolve diff --git a/src/content/api/parser.mdx b/src/content/api/parser.mdx index 963554c7259f..8063aa75fcae 100644 --- a/src/content/api/parser.mdx +++ b/src/content/api/parser.mdx @@ -351,35 +351,47 @@ Called for every specifier of every `export`-import statement. ### varDeclaration -`SyncBailHook` +`HookMap` + +Called when parsing a variable declaration, once for each declared identifier. The callback receives the `Identifier` node. -Called when parsing a variable declaration. +- Hook Parameters: `identifier` +- Callback Parameters: `identifier` -- Callback Parameters: `declaration` +```js +const a = 1; + +parser.hooks.varDeclaration.for("a").tap("MyPlugin", (identifier) => { + // identifier is the `Identifier` node of a +}); +``` ### varDeclarationLet -`SyncBailHook` +`HookMap` Called when parsing a variable declaration defined using `let` -- Callback Parameters: `declaration` +- Hook Parameters: `identifier` +- Callback Parameters: `identifier` ### varDeclarationConst -`SyncBailHook` +`HookMap` Called when parsing a variable declaration defined using `const` -- Callback Parameters: `declaration` +- Hook Parameters: `identifier` +- Callback Parameters: `identifier` ### varDeclarationVar -`SyncBailHook` +`HookMap` Called when parsing a variable declaration defined using `var` -- Callback Parameters: `declaration` +- Hook Parameters: `identifier` +- Callback Parameters: `identifier` ### canRename @@ -416,28 +428,11 @@ const a = b; parser.hooks.rename.for("b").tap("MyPlugin", (expression) => {}); ``` -### assign (before parsing assigned expression) - -`SyncBailHook` - -Called when parsing an `AssignmentExpression` before parsing the assigned expression. - -- Hook Parameters: `identifier` -- Callback Parameters: `expression` - -```js -a += b; - -parser.hooks.assign.for("a").tap("MyPlugin", (expression) => { - // this is called before parsing b -}); -``` - -### assign (before parsing target) +### assign `SyncBailHook` -Called when parsing an `AssignmentExpression` before parsing the assign expression. +Called when parsing an `AssignmentExpression`, after the assigned expression has been walked and before the target is walked. Returning `true` prevents the target from being walked. - Hook Parameters: `identifier` - Callback Parameters: `expression` @@ -446,7 +441,7 @@ Called when parsing an `AssignmentExpression` before parsing the assign expressi a += b; parser.hooks.assign.for("a").tap("MyPlugin", (expression) => { - // this is called before parsing a + // this is called after b has been walked, before a is walked }); ``` diff --git a/src/content/api/plugins.mdx b/src/content/api/plugins.mdx index acc36c2755a6..1f53240a2c1a 100644 --- a/src/content/api/plugins.mdx +++ b/src/content/api/plugins.mdx @@ -28,14 +28,14 @@ webpack's plugin interface. ## Tapable This small library is a core utility in webpack but can also be used elsewhere -to provide a similar plugin interface. Many objects in webpack extend the -`Tapable` class. The class exposes `tap`, `tapAsync`, and `tapPromise` methods +to provide a similar plugin interface. Many objects in webpack expose a +`hooks` object of tapable hooks. Each hook exposes `tap` and, depending on its type, `tapAsync` and `tapPromise` methods which plugins can use to inject custom build steps that will be fired throughout a compilation. Please see the [documentation](https://github.com/webpack/tapable) to learn more. An understanding of the three `tap` methods, as well as the hooks that -provide them, is crucial. The objects that extend `Tapable` (e.g. the compiler), +provide them, is crucial. The objects that expose hooks (e.g. the compiler), the hooks they provide, and each hook's type (e.g. the `SyncHook`) will be noted. @@ -61,15 +61,12 @@ However, for `run` which utilizes the `AsyncHook`, we can utilize `tapAsync` or `tapPromise` (as well as `tap`): ```js -compiler.hooks.run.tapAsync( - "MyPlugin", - (source, target, routesList, callback) => { - console.log("Asynchronously tapping the run hook."); - callback(); - }, -); +compiler.hooks.run.tapAsync("MyPlugin", (compiler, callback) => { + console.log("Asynchronously tapping the run hook."); + callback(); +}); -compiler.hooks.run.tapPromise("MyPlugin", (source, target, routesList) => +compiler.hooks.run.tapPromise("MyPlugin", (compiler) => new Promise((resolve) => { setTimeout(resolve, 1000); }).then(() => { @@ -77,15 +74,12 @@ compiler.hooks.run.tapPromise("MyPlugin", (source, target, routesList) => }), ); -compiler.hooks.run.tapPromise( - "MyPlugin", - async (source, target, routesList) => { - await new Promise((resolve) => { - setTimeout(resolve, 1000); - }); - console.log("Asynchronously tapping the run hook with a delay."); - }, -); +compiler.hooks.run.tapPromise("MyPlugin", async (compiler) => { + await new Promise((resolve) => { + setTimeout(resolve, 1000); + }); + console.log("Asynchronously tapping the run hook with a delay."); +}); ``` The moral of the story is that there are a variety of ways to `hook` into the @@ -149,23 +143,19 @@ Plugins can report progress via [`ProgressPlugin`](/plugins/progress-plugin/), w It is possible to customize the printed output by passing different arguments to the `reportProgress` function of [`ProgressPlugin`](/plugins/progress-plugin/). -To report progress, a plugin must `tap` into a hook using the `context: true` option: +To report progress, a plugin gets the reporter with `ProgressPlugin.getReporter(compiler)` and calls it from a normal `tap`. `getReporter` returns `undefined` when no `ProgressPlugin` is active: ```js -compiler.hooks.emit.tapAsync( - { - name: "MyPlugin", - context: true, - }, - (context, compiler, callback) => { - const reportProgress = context && context.reportProgress; - if (reportProgress) reportProgress(0.95, "Starting work"); - setTimeout(() => { - if (reportProgress) reportProgress(0.95, "Done work"); - callback(); - }, 1000); - }, -); +import { ProgressPlugin } from "webpack"; + +compiler.hooks.emit.tapAsync("MyPlugin", (compilation, callback) => { + const reportProgress = ProgressPlugin.getReporter(compiler); + if (reportProgress) reportProgress(0.95, "Starting work"); + setTimeout(() => { + if (reportProgress) reportProgress(0.95, "Done work"); + callback(); + }, 1000); +}); ``` The `reportProgress` function may be called with these arguments: diff --git a/src/content/api/stats.mdx b/src/content/api/stats.mdx index 673d0509419d..65ee4176204b 100644 --- a/src/content/api/stats.mdx +++ b/src/content/api/stats.mdx @@ -46,7 +46,7 @@ The top-level structure of the output JSON file is fairly straightforward but th "modules": [ // A list of module objects ], - "entryPoints": { + "entrypoints": { // A list of entry objects }, "errors": [ @@ -121,10 +121,7 @@ The `chunks` object will also contain a list of `origins` describing how the giv "moduleId": 0, // The ID of the module "moduleIdentifier": "(webpack)\\test\\browsertest\\lib\\index.web.js", // Path to the module "moduleName": "./lib/index.web.js", // Relative path to the module - "name": "main", // The name of the chunk - "reasons": [ - // A list of the same `reasons` found in [module objects](#module-objects) - ] + "request": "./lib/index.web.js" // The request that created the chunk group } ``` @@ -137,18 +134,18 @@ What good would these statistics be without some description of the compiled app "assets": [ // A list of [asset objects](#asset-objects) ], - "built": true, // Indicates that the module went through [Loaders](/concepts/loaders), Parsing, and Code Generation + "built": true, // Indicates that the module was built ([Loaders](/concepts/loaders) and Parsing) in this compilation "cacheable": true, // Whether or not this module is cacheable "chunks": [ // IDs of chunks that contain this module ], + "codeGenerated": true, // Indicates that the module went through Code Generation in this compilation "errors": 0, // Number of errors when resolving or processing the module "failed": false, // Whether or not compilation failed on this module "id": 0, // The ID of the module (analogous to [`module.id`](/api/module-variables/#moduleid-commonjs)) "identifier": "(webpack)\\test\\browsertest\\lib\\index.web.js", // A unique ID used internally "name": "./lib/index.web.js", // Path to the actual file "optional": false, // All requests to this module are with `try... catch` blocks (irrelevant with ESM) - "prefetched": false, // Indicates whether or not the module was [prefetched](/plugins/prefetch-plugin) "profile": { // Module specific compilation stats corresponding to the [`--profile` flag](/api/cli/#profiling) (in milliseconds) "building": 73, // Loading and parsing