Skip to content

Commit 55de20f

Browse files
committed
docs(api): add this.getOptions schema validation example
1 parent b9ad103 commit 55de20f

1 file changed

Lines changed: 31 additions & 0 deletions

File tree

src/content/api/loaders.mdx

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ contributors:
1515
- chenxsan
1616
- jamesgeorge007
1717
- alexeyr
18+
- raj-sapalya
1819
---
1920

2021
A loader is a JavaScript module that exports a function. The [loader runner](https://github.com/webpack/loader-runner) calls this function and passes the result of the previous loader or the resource file into it. The `this` context of the function is filled-in by webpack and the [loader runner](https://github.com/webpack/loader-runner) with some useful methods that allow the loader (among other things) to change its invocation style to async, or get query parameters.
@@ -373,6 +374,36 @@ Extracts given loader options. Optionally, accepts JSON schema as an argument.
373374

374375
T> Since webpack 5, `this.getOptions` is available in loader context. It substitutes `getOptions` method from [loader-utils](https://github.com/webpack/loader-utils#getoptions).
375376

377+
You can pass a JSON Schema to validate loader options automatically.
378+
If a user passes an invalid or unknown option, webpack throws a
379+
descriptive error at build start rather than failing silently.
380+
381+
```js
382+
const schema = {
383+
type: "object",
384+
properties: {
385+
prefix: {
386+
type: "string",
387+
description: "String to prepend to each file.",
388+
},
389+
minify: {
390+
type: "boolean",
391+
description: "Whether to minify the output.",
392+
},
393+
},
394+
additionalProperties: false,
395+
};
396+
397+
export default function (source) {
398+
const options = this.getOptions(schema);
399+
const prefix = options.prefix ?? "";
400+
return `${prefix}\n${source}`;
401+
}
402+
```
403+
404+
T> `additionalProperties: false` causes webpack to throw if the user
405+
passes an unrecognized option, catching misconfiguration at build start.
406+
376407
### this.getResolve
377408
378409
```ts

0 commit comments

Comments
 (0)