Skip to content

Commit ad76374

Browse files
patak-devsapphi-redbluwy
authored
feat: extended applyToEnvironment and perEnvironmentPlugin (#18544)
Co-authored-by: 翠 / green <[email protected]> Co-authored-by: Bjorn Lu <[email protected]>
1 parent 39f50cc commit ad76374

File tree

2 files changed

+35
-3
lines changed

2 files changed

+35
-3
lines changed

changes/shared-plugins-during-build.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,11 +59,11 @@ function PerEnvironmentCountTransformedModulesPlugin() {
5959
}
6060
```
6161

62-
To simplify this pattern, internally in Vite, we use a `usePerEnvironmentState` helper:
62+
To simplify this pattern, Vite exports a `perEnvironmentState` helper:
6363

6464
```js
6565
function PerEnvironmentCountTransformedModulesPlugin() {
66-
const state = usePerEnvironmentState<{ count: number }>(() => ({ count: 0 }))
66+
const state = perEnvironmentState<{ count: number }>(() => ({ count: 0 }))
6767
return {
6868
name: 'count-transformed-modules',
6969
perEnvironmentStartEndDuringDev: true,

guide/api-environment-plugins.md

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,8 @@ const UnoCssPlugin = () => {
142142
// use global hooks normally
143143
},
144144
applyToEnvironment(environment) {
145-
// return true if this plugin should be active in this environment
145+
// return true if this plugin should be active in this environment,
146+
// or return a new plugin to replace it.
146147
// if the hook is not used, the plugin is active in all environments
147148
},
148149
resolveId(id, importer) {
@@ -152,6 +153,37 @@ const UnoCssPlugin = () => {
152153
}
153154
```
154155
156+
If a plugin isn't environment aware and has state that isn't keyed on the current environment, the `applyToEnvironment` hook allows to easily make it per-environment.
157+
158+
```js
159+
import { nonShareablePlugin } from 'non-shareable-plugin'
160+
161+
export default defineConfig({
162+
plugins: [
163+
{
164+
name: 'per-environment-plugin',
165+
applyToEnvironment(environment) {
166+
return nonShareablePlugin({ outputName: environment.name })
167+
},
168+
},
169+
],
170+
})
171+
```
172+
173+
Vite exports a `perEnvironmentPlugin` helper to simplify these cases where no other hooks are required:
174+
175+
```js
176+
import { nonShareablePlugin } from 'non-shareable-plugin'
177+
178+
export default defineConfig({
179+
plugins: [
180+
perEnvironmentPlugin('per-environment-plugin', (environment) =>
181+
nonShareablePlugin({ outputName: environment.name }),
182+
),
183+
],
184+
})
185+
```
186+
155187
## Environment in build hooks
156188
157189
In the same way as during dev, plugin hooks also receive the environment instance during build, replacing the `ssr` boolean.

0 commit comments

Comments
 (0)