Skip to content

Commit 40053d1

Browse files
authored
feat: extended applyToEnvironment and perEnvironmentPlugin (#1727)
resolve #1726 vitejs/vite@8fa70cd の反映です。
1 parent d068c84 commit 40053d1

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-
このパターンを簡素化するために、Vite の内部では、`usePerEnvironmentState` ヘルパーを使用しています:
62+
このパターンを簡素化するために、Vite `perEnvironmentState` ヘルパーをエクスポートしています:
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
// グローバルフックを通常どおり使用
143143
},
144144
applyToEnvironment(environment) {
145-
// このプラグインがこの環境でアクティブになる必要がある場合は true を返します
145+
// このプラグインがこの環境でアクティブになる必要がある場合は true を返し、
146+
// そうでない場合は、それを置き換える新しいプラグインを返します。
146147
// フックが使用されていない場合、プラグインはすべての環境でアクティブになります
147148
},
148149
resolveId(id, importer) {
@@ -152,6 +153,37 @@ const UnoCssPlugin = () => {
152153
}
153154
```
154155
156+
プラグインが環境を認識せず、現在の環境に基づかない状態を持っている場合、`applyToEnvironment` フックを利用することで、簡単に環境別に対応するものに変えられます。
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 は `perEnvironmentPlugin` ヘルパーをエクスポートしています:
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
開発時と同じように、プラグインフックもビルド時に環境インスタンスを受け取り、`ssr` ブール値を置き換えます。

0 commit comments

Comments
 (0)