From f19282f003f64093518290a61446403b1f022d18 Mon Sep 17 00:00:00 2001 From: Andy Li Date: Fri, 10 Sep 2021 22:14:07 +0800 Subject: [PATCH] feat: allow `apply` condition to be a function (#4857) --- docs/guide/api-plugin.md | 9 +++++++++ packages/vite/src/node/config.ts | 10 +++++++++- packages/vite/src/node/plugin.ts | 4 ++-- 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/docs/guide/api-plugin.md b/docs/guide/api-plugin.md index 8de592b53bc6f6..0a4696595430af 100644 --- a/docs/guide/api-plugin.md +++ b/docs/guide/api-plugin.md @@ -414,6 +414,15 @@ function myPlugin() { } ``` +A function can also be used for more precise control: + +```js +apply(config, { command }) { + // apply only on build but not for SSR + return command === 'build' && !config.build.ssr +} +``` + ## Rollup Plugin Compatibility A fair number of Rollup plugins will work directly as a Vite plugin (e.g. `@rollup/plugin-alias` or `@rollup/plugin-json`), but not all of them, since some plugin hooks do not make sense in an unbundled dev server context. diff --git a/packages/vite/src/node/config.ts b/packages/vite/src/node/config.ts index 19274a725d785a..272331e47b87eb 100644 --- a/packages/vite/src/node/config.ts +++ b/packages/vite/src/node/config.ts @@ -285,7 +285,15 @@ export async function resolveConfig( // resolve plugins const rawUserPlugins = (config.plugins || []).flat().filter((p) => { - return p && (!p.apply || p.apply === command) + if (!p) { + return false + } else if (!p.apply) { + return true + } else if (typeof p.apply === 'function') { + return p.apply({ ...config, mode }, configEnv) + } else { + return p.apply === command + } }) as Plugin[] const [prePlugins, normalPlugins, postPlugins] = sortUserPlugins(rawUserPlugins) diff --git a/packages/vite/src/node/plugin.ts b/packages/vite/src/node/plugin.ts index 012c32e0fa6dfb..3af59bbd09b62c 100644 --- a/packages/vite/src/node/plugin.ts +++ b/packages/vite/src/node/plugin.ts @@ -50,9 +50,9 @@ export interface Plugin extends RollupPlugin { */ enforce?: 'pre' | 'post' /** - * Apply the plugin only for serve or for build. + * Apply the plugin only for serve or build, or on certain conditions. */ - apply?: 'serve' | 'build' + apply?: 'serve' | 'build' | ((config: UserConfig, env: ConfigEnv) => boolean) /** * Modify vite config before it's resolved. The hook can either mutate the * passed-in config directly, or return a partial config object that will be