Skip to content

Commit

Permalink
feat: allow apply condition to be a function (#4857)
Browse files Browse the repository at this point in the history
  • Loading branch information
andylizi committed Sep 10, 2021
1 parent 5c5811e commit f19282f
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 3 deletions.
9 changes: 9 additions & 0 deletions docs/guide/api-plugin.md
Expand Up @@ -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.
Expand Down
10 changes: 9 additions & 1 deletion packages/vite/src/node/config.ts
Expand Up @@ -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)
Expand Down
4 changes: 2 additions & 2 deletions packages/vite/src/node/plugin.ts
Expand Up @@ -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
Expand Down

0 comments on commit f19282f

Please sign in to comment.