From 48446d1ba31a7561a64258e1fbe24cf2ec2d30bd Mon Sep 17 00:00:00 2001 From: TAKAHASHI Shuuji Date: Thu, 14 Nov 2024 09:34:29 +0900 Subject: [PATCH] feat: extended applyToEnvironment and perEnvironmentPlugin MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit resolve #1726 https://github.com/vitejs/vite/commit/8fa70cdfa65ce8254ab8da8be0d92614126764c0 の反映です。 --- changes/shared-plugins-during-build.md | 4 +-- guide/api-environment-plugins.md | 34 +++++++++++++++++++++++++- 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/changes/shared-plugins-during-build.md b/changes/shared-plugins-during-build.md index d9fc91ac..a4a27e40 100644 --- a/changes/shared-plugins-during-build.md +++ b/changes/shared-plugins-during-build.md @@ -59,11 +59,11 @@ function PerEnvironmentCountTransformedModulesPlugin() { } ``` -このパターンを簡素化するために、Vite の内部では、`usePerEnvironmentState` ヘルパーを使用しています: +このパターンを簡素化するために、Vite は `perEnvironmentState` ヘルパーをエクスポートしています: ```js function PerEnvironmentCountTransformedModulesPlugin() { - const state = usePerEnvironmentState<{ count: number }>(() => ({ count: 0 })) + const state = perEnvironmentState<{ count: number }>(() => ({ count: 0 })) return { name: 'count-transformed-modules', perEnvironmentStartEndDuringDev: true, diff --git a/guide/api-environment-plugins.md b/guide/api-environment-plugins.md index d2d3e7d3..c3c0cbc2 100644 --- a/guide/api-environment-plugins.md +++ b/guide/api-environment-plugins.md @@ -142,7 +142,8 @@ const UnoCssPlugin = () => { // グローバルフックを通常どおり使用 }, applyToEnvironment(environment) { - // このプラグインがこの環境でアクティブになる必要がある場合は true を返します + // このプラグインがこの環境でアクティブになる必要がある場合は true を返し、 + // そうでない場合は、それを置き換える新しいプラグインを返します。 // フックが使用されていない場合、プラグインはすべての環境でアクティブになります }, resolveId(id, importer) { @@ -152,6 +153,37 @@ const UnoCssPlugin = () => { } ``` +プラグインが環境を認識せず、現在の環境に基づかない状態を持っている場合、`applyToEnvironment` フックを利用することで、簡単に環境別に対応するものに変えられます。 + +```js +import { nonShareablePlugin } from 'non-shareable-plugin' + +export default defineConfig({ + plugins: [ + { + name: 'per-environment-plugin', + applyToEnvironment(environment) { + return nonShareablePlugin({ outputName: environment.name }) + }, + }, + ], +}) +``` + +以下のような他のフックが不要なケースを簡略化するために、Vite は `perEnvironmentPlugin` ヘルパーをエクスポートしています: + +```js +import { nonShareablePlugin } from 'non-shareable-plugin' + +export default defineConfig({ + plugins: [ + perEnvironmentPlugin('per-environment-plugin', (environment) => + nonShareablePlugin({ outputName: environment.name }), + ), + ], +}) +``` + ## ビルドフックの環境 {#environment-in-build-hooks} 開発時と同じように、プラグインフックもビルド時に環境インスタンスを受け取り、`ssr` ブール値を置き換えます。