diff --git a/src/content/api/compiler-hooks.mdx b/src/content/api/compiler-hooks.mdx index dbcdbf05cf5b..d0ecb8d09794 100644 --- a/src/content/api/compiler-hooks.mdx +++ b/src/content/api/compiler-hooks.mdx @@ -89,6 +89,27 @@ Triggered after resolver setup is complete. - Callback Parameters: `compiler` +### validate + +`SyncHook` + + + +Called to register validation work for webpack configuration, plugins, and loaders. Plugin authors can tap this hook and use `compiler.validate(...)` to participate in webpack's built-in validation flow. + +W> The hook is always available. `compiler.validate(...)` skips validation when `validate: false` is set. With `experiments.futureDefaults`, webpack keeps validation enabled by default in development and disables it by default in production. + +```js +compiler.hooks.validate.tap("MyPlugin", () => { + compiler.validate( + () => require("./schema/MyPlugin.json"), + options, + { name: "My Plugin", baseDataPath: "options" }, + (validatedOptions) => require("./schema/MyPlugin.check")(validatedOptions), + ); +}); +``` + ### initialize `SyncHook` diff --git a/src/content/contribute/writing-a-plugin.mdx b/src/content/contribute/writing-a-plugin.mdx index 52b369463b41..d9fe07662278 100644 --- a/src/content/contribute/writing-a-plugin.mdx +++ b/src/content/contribute/writing-a-plugin.mdx @@ -89,7 +89,7 @@ export default { }; ``` -Use [`schema-utils`](https://github.com/webpack/schema-utils) in order to validate the options being passed through the plugin options. Here is an example: +A familiar way to validate plugin options in webpack versions **before `5.106`** is to use [`schema-utils`](https://github.com/webpack/schema-utils) in the constructor: ```js import { validate } from "schema-utils"; @@ -116,6 +116,27 @@ export default class HelloWorldPlugin { } ``` +Starting in webpack `5.106`, you can move that validation into `apply()` by tapping `compiler.hooks.validate` and calling `compiler.validate(...)` instead: + +```js +export default class HelloWorldPlugin { + constructor(options = {}) { + this.options = options; + } + + apply(compiler) { + compiler.hooks.validate.tap("HelloWorldPlugin", () => { + compiler.validate( + () => require("./schema/hello-world-plugin.json"), + this.options, + ); + }); + } +} +``` + +W> This validation flow is skipped when webpack is configured with `validate: false`. With `experiments.futureDefaults`, validation is enabled by default in development mode and disabled by default in production mode. + ## Compiler and Compilation Among the two most important resources while developing plugins are the [`compiler`](/api/node/#compiler-instance) and [`compilation`](/api/compilation-hooks/) objects. Understanding their roles is an important first step in extending the webpack engine.