Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: allow apply condition to be a function #4857

Merged
merged 2 commits into from
Sep 10, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions docs/guide/api-plugin.md
Original file line number Diff line number Diff line change
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
andylizi marked this conversation as resolved.
Show resolved Hide resolved
}
```

## 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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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