Skip to content

Commit 3f3f870

Browse files
authored
docs(contribute): add pitching loaders section to writing-a-loader (#8192)
1 parent 166da89 commit 3f3f870

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

src/content/contribute/writing-a-loader.mdx

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ contributors:
1111
- dev-itsheng
1212
- evenstensberg
1313
- hagemaruwu
14+
- raj-sapalya
1415
---
1516

1617
A loader is a node module that exports a function. This function is called when a resource should be transformed by this loader. The given function will have access to the [Loader API](/api/loaders/) using the `this` context provided to it.
@@ -101,6 +102,52 @@ export default {
101102
};
102103
```
103104

105+
## Pitching loaders
106+
107+
Loaders normally run **right to left**. A loader can also export a
108+
`pitch` function, which runs **left to right** before the normal phase
109+
begins. This allows a loader to pass data to its own normal phase or
110+
short-circuit the remaining loader chain.
111+
112+
```js
113+
// my-loader.js
114+
export default function (source) {
115+
// Normal phase — runs right to left
116+
const prefix = this.data.value ?? "";
117+
return `${prefix}\n${source}`;
118+
}
119+
120+
export function pitch(remainingRequest, precedingRequest, data) {
121+
// Pitch phase — runs left to right before normal loaders
122+
data.value = "/* processed by my-loader */";
123+
}
124+
```
125+
126+
T> `data` is shared only between the `pitch` and normal functions of
127+
the same loader. It is not shared across different loaders in
128+
the chain.
129+
130+
### Short-circuiting the loader chain
131+
132+
If a `pitch` function returns a value, webpack skips the remaining
133+
loaders to the right and reverses immediately. This can be useful when
134+
you want to generate module code early and bypass the normal phase.
135+
136+
```js
137+
export function pitch(remainingRequest) {
138+
return `
139+
import style from ${JSON.stringify(`!!${remainingRequest}`)};
140+
const el = document.createElement("style");
141+
el.textContent = style;
142+
document.head.appendChild(el);
143+
`;
144+
}
145+
```
146+
147+
W> When a `pitch` function returns a value, the default export of that
148+
loader does not run. Only use this pattern when you intend to replace
149+
the normal processing pipeline.
150+
104151
## Guidelines
105152
106153
The following guidelines should be followed when writing a loader. They are ordered in terms of importance and some only apply in certain scenarios, read the detailed sections that follow for more information.

0 commit comments

Comments
 (0)