Skip to content

Commit 2ade5e4

Browse files
docs: per-environment state in plugins (#20239) (#837)
Co-authored-by: Rush Ali <s0aPii.ra@googlemail.com>
1 parent c525905 commit 2ade5e4

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

docs/guide/api-environment-plugins.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,29 @@ The hook can choose to:
126126
}
127127
```
128128
129+
## Per-environment State in Plugins
130+
131+
Given that the same plugin instance is used for different environments, the plugin state needs to be keyed with `this.environment`. This is the same pattern the ecosystem has already been using to keep state about modules using the `ssr` boolean as key to avoid mixing client and ssr modules state. A `Map<Environment, State>` can be used to keep the state for each environment separately. Note that for backward compatibility, `buildStart` and `buildEnd` are only called for the client environment without the `perEnvironmentStartEndDuringDev: true` flag.
132+
133+
```js
134+
function PerEnvironmentCountTransformedModulesPlugin() {
135+
const state = new Map<Environment, { count: number }>()
136+
return {
137+
name: 'count-transformed-modules',
138+
perEnvironmentStartEndDuringDev: true,
139+
buildStart() {
140+
state.set(this.environment, { count: 0 })
141+
},
142+
transform(id) {
143+
state.get(this.environment).count++
144+
},
145+
buildEnd() {
146+
console.log(this.environment.name, state.get(this.environment).count)
147+
}
148+
}
149+
}
150+
```
151+
129152
## Per-environment Plugins
130153
131154
A plugin can define what are the environments it should apply to with the `applyToEnvironment` function.

0 commit comments

Comments
 (0)