Skip to content

Commit

Permalink
feat: back to environmentPlugins hook (#16732)
Browse files Browse the repository at this point in the history
  • Loading branch information
patak-dev authored May 20, 2024
1 parent 8ee7fcd commit 54c219e
Show file tree
Hide file tree
Showing 14 changed files with 121 additions and 174 deletions.
28 changes: 14 additions & 14 deletions docs/guide/api-vite-environment.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,12 @@ class DevEnvironment {
* Resolved plugins for this environment, including the ones
* created using the per-environment `create` hook
*/
plugins: IsolatedPlugin[]
plugins: EnvironmentPlugin[]
/**
* Allows to resolve, load, and transform code through the
* environment plugins pipeline
*/
pluginContainer: IsolatedPluginContatiner
pluginContainer: EnvironmentPluginContainer
/**
* Resolved config options for this environment. Options at the server
* global scope are taken as defaults for all environments, and can
Expand Down Expand Up @@ -888,19 +888,19 @@ function myPlugin() {
// Share state among all environments in dev and build
const sharedState = ...

const plugin = (environment) => {
// Isolated state for each environment during dev and build
const isolatedState = ...

return {
name: 'isolated-plugin',
transform(code, id) { ... }
}
return {
name: 'with-environment-plugins',
environmentPlugins(environment) {
// Isolated state for each environment during dev and build
const isolatedState = ...
return {
name: 'per-environment-plugin',
transform(code, id) { ... },
}
},
// Opt-in into a single instance for all environments
sharedDuringBuild: true
}

// Opt-in into a single instance for all environments
plugin.sharedDuringBuild = true
return plugin
}
```
Expand Down
22 changes: 8 additions & 14 deletions packages/vite/src/node/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ import {
partialEncodeURIPath,
requireResolveFromRootWithFallback,
} from './utils'
import { resolveIsolatedPlugins } from './plugin'
import { resolveEnvironmentPlugins } from './plugin'
import { manifestPlugin } from './plugins/manifest'
import type { Logger } from './logger'
import { dataURIPlugin } from './plugins/dataUri'
Expand All @@ -66,7 +66,7 @@ import { mergeConfig } from './publicUtils'
import { webWorkerPostPlugin } from './plugins/worker'
import { getHookHandler } from './plugins'
import { Environment } from './environment'
import type { IsolatedPluginConstructor, Plugin, PluginContext } from './plugin'
import type { Plugin, PluginContext } from './plugin'

export interface BuildEnvironmentOptions {
/**
Expand Down Expand Up @@ -534,9 +534,7 @@ export async function build(
function resolveConfigToBuild(
inlineConfig: InlineConfig = {},
patchConfig?: (config: ResolvedConfig) => void,
patchPlugins?: (
resolvedPlugins: (Plugin | IsolatedPluginConstructor)[],
) => void,
patchPlugins?: (resolvedPlugins: Plugin[]) => void,
) {
return resolveConfig(
inlineConfig,
Expand Down Expand Up @@ -610,11 +608,9 @@ export async function buildEnvironment(

// inject environment and ssr arg to plugin load/transform hooks
// TODO: rework lib mode
const plugins = (
libOptions
? (config.plugins.filter((p) => typeof p !== 'function') as Plugin[])
: environment.plugins
).map((p) => injectEnvironmentToHooks(p, environment))
const plugins = (libOptions ? config : environment).plugins.map((p) =>
injectEnvironmentToHooks(p, environment),
)

const rollupOptions: RollupOptions = {
preserveEntrySignatures: ssr
Expand Down Expand Up @@ -1443,7 +1439,7 @@ export class BuildEnvironment extends Environment {
return
}
this._inited = true
this._plugins = await resolveIsolatedPlugins(this)
this._plugins = await resolveEnvironmentPlugins(this)
}
}

Expand Down Expand Up @@ -1529,9 +1525,7 @@ export async function createBuilder(
lib: false,
}
}
const patchPlugins = (
resolvedPlugins: (Plugin | IsolatedPluginConstructor)[],
) => {
const patchPlugins = (resolvedPlugins: Plugin[]) => {
// Force opt-in shared plugins
const environmentPlugins = [...resolvedPlugins]
let validMixedPlugins = true
Expand Down
49 changes: 15 additions & 34 deletions packages/vite/src/node/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ import {
} from './constants'
import type {
HookHandler,
IsolatedPluginConstructor,
Plugin,
PluginEnvironment,
PluginOption,
Expand Down Expand Up @@ -83,8 +82,8 @@ import type { LogLevel, Logger } from './logger'
import { createLogger } from './logger'
import type { DepOptimizationConfig, DepOptimizationOptions } from './optimizer'
import type { JsonOptions } from './plugins/json'
import type { IsolatedPluginContainer } from './server/pluginContainer'
import { createIsolatedPluginContainer } from './server/pluginContainer'
import type { EnvironmentPluginContainer } from './server/pluginContainer'
import { createEnvironmentPluginContainer } from './server/pluginContainer'
import type { PackageCache } from './packages'
import { findNearestPackageData } from './packages'
import { loadEnv, resolveEnvPrefix } from './env'
Expand Down Expand Up @@ -538,7 +537,7 @@ export type ResolvedConfig = Readonly<
resolve: Required<ResolveOptions> & {
alias: Alias[]
}
plugins: readonly (Plugin | IsolatedPluginConstructor)[]
plugins: readonly Plugin[]
css: ResolvedCSSOptions
esbuild: ESBuildOptions | false
server: ResolvedServerOptions
Expand Down Expand Up @@ -762,9 +761,7 @@ export async function resolveConfig(
defaultNodeEnv = 'development',
isPreview = false,
patchConfig: ((config: ResolvedConfig) => void) | undefined = undefined,
patchPlugins:
| ((resolvedPlugins: (Plugin | IsolatedPluginConstructor)[]) => void)
| undefined = undefined,
patchPlugins: ((resolvedPlugins: Plugin[]) => void) | undefined = undefined,
): Promise<ResolvedConfig> {
let config = inlineConfig
let configFileDependencies: string[] = []
Expand Down Expand Up @@ -805,7 +802,7 @@ export async function resolveConfig(
mode = inlineConfig.mode || config.mode || mode
configEnv.mode = mode

const filterPlugin = (p: Plugin | IsolatedPluginConstructor) => {
const filterPlugin = (p: Plugin) => {
if (!p) {
return false
} else if (typeof p === 'function' || !p.apply) {
Expand All @@ -819,18 +816,10 @@ export async function resolveConfig(

// resolve plugins
const rawPlugins = (
(await asyncFlatten(config.plugins || [])) as (
| Plugin
| IsolatedPluginConstructor
)[]
(await asyncFlatten(config.plugins || [])) as Plugin[]
).filter(filterPlugin)

const sharedPlugins = rawPlugins.filter(
(plugin) => typeof plugin !== 'function',
) as Plugin[]

const [prePlugins, normalPlugins, postPlugins] =
sortUserPlugins(sharedPlugins)
const [prePlugins, normalPlugins, postPlugins] = sortUserPlugins(rawPlugins)

const isBuild = command === 'build'

Expand Down Expand Up @@ -1226,12 +1215,12 @@ export async function resolveConfig(
*/
createResolver(options) {
const alias: {
client?: IsolatedPluginContainer
ssr?: IsolatedPluginContainer
client?: EnvironmentPluginContainer
ssr?: EnvironmentPluginContainer
} = {}
const resolver: {
client?: IsolatedPluginContainer
ssr?: IsolatedPluginContainer
client?: EnvironmentPluginContainer
ssr?: EnvironmentPluginContainer
} = {}
const environments = this.environments ?? resolvedEnvironments
const createPluginContainer = async (
Expand All @@ -1242,7 +1231,7 @@ export async function resolveConfig(
// environment so we can safely cast to a base Environment instance to a
// PluginEnvironment here
const environment = new Environment(environmentName, this)
const pluginContainer = await createIsolatedPluginContainer(
const pluginContainer = await createEnvironmentPluginContainer(
environment as PluginEnvironment,
plugins,
)
Expand All @@ -1256,7 +1245,7 @@ export async function resolveConfig(
ssr?: boolean,
): Promise<PartialResolvedId | null> {
const environmentName = ssr ? 'ssr' : 'client'
let container: IsolatedPluginContainer
let container: EnvironmentPluginContainer
if (aliasOnly) {
let aliasContainer = alias[environmentName]
if (!aliasContainer) {
Expand Down Expand Up @@ -1318,18 +1307,10 @@ export async function resolveConfig(

// Backward compatibility hook used in builder, opt-in to shared plugins during build
patchPlugins?.(resolvedPlugins)
;(resolved.plugins as (Plugin | IsolatedPluginConstructor)[]) =
resolvedPlugins
;(resolved.plugins as Plugin[]) = resolvedPlugins

// TODO: Deprecate config.getSortedPlugins and config.getSortedPluginHooks
Object.assign(
resolved,
createPluginHookUtils(
resolved.plugins.filter(
(plugin) => typeof plugin !== 'function',
) as Plugin[],
),
)
Object.assign(resolved, createPluginHookUtils(resolved.plugins))

// call configResolved hooks
await Promise.all(
Expand Down
6 changes: 3 additions & 3 deletions packages/vite/src/node/environment.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import colors from 'picocolors'
import type { Logger } from './logger'
import type { ResolvedConfig, ResolvedEnvironmentOptions } from './config'
import type { IsolatedPlugin } from './plugin'
import type { EnvironmentPlugin } from './plugin'

export class Environment {
name: string

config: ResolvedConfig
options: ResolvedEnvironmentOptions

get plugins(): IsolatedPlugin[] {
get plugins(): EnvironmentPlugin[] {
if (!this._plugins)
throw new Error(
`${this.name} environment.plugins called before initialized`,
Expand All @@ -19,7 +19,7 @@ export class Environment {
/**
* @internal
*/
_plugins: IsolatedPlugin[] | undefined
_plugins: EnvironmentPlugin[] | undefined
/**
* @internal
*/
Expand Down
12 changes: 6 additions & 6 deletions packages/vite/src/node/idResolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import aliasPlugin from '@rollup/plugin-alias'
import type { ResolvedConfig } from './config'
import type { Environment } from './environment'
import type { PluginEnvironment } from './plugin'
import type { IsolatedPluginContainer } from './server/pluginContainer'
import { createIsolatedPluginContainer } from './server/pluginContainer'
import type { EnvironmentPluginContainer } from './server/pluginContainer'
import { createEnvironmentPluginContainer } from './server/pluginContainer'
import { resolvePlugin } from './plugins/resolve'
import type { InternalResolveOptions } from './plugins/resolve'
import { getFsUtils } from './fsUtils'
Expand All @@ -26,15 +26,15 @@ export function createIdResolver(
): ResolveIdFn {
const scan = options?.scan

const pluginContainerMap = new Map<Environment, IsolatedPluginContainer>()
const pluginContainerMap = new Map<Environment, EnvironmentPluginContainer>()
async function resolve(
environment: PluginEnvironment,
id: string,
importer?: string,
): Promise<PartialResolvedId | null> {
let pluginContainer = pluginContainerMap.get(environment)
if (!pluginContainer) {
pluginContainer = await createIsolatedPluginContainer(environment, [
pluginContainer = await createEnvironmentPluginContainer(environment, [
aliasPlugin({ entries: config.resolve.alias }), // TODO: resolve.alias per environment?
resolvePlugin({
root: config.root,
Expand All @@ -56,7 +56,7 @@ export function createIdResolver(

const aliasOnlyPluginContainerMap = new Map<
Environment,
IsolatedPluginContainer
EnvironmentPluginContainer
>()
async function resolveAlias(
environment: PluginEnvironment,
Expand All @@ -65,7 +65,7 @@ export function createIdResolver(
): Promise<PartialResolvedId | null> {
let pluginContainer = aliasOnlyPluginContainerMap.get(environment)
if (!pluginContainer) {
pluginContainer = await createIsolatedPluginContainer(environment, [
pluginContainer = await createEnvironmentPluginContainer(environment, [
aliasPlugin({ entries: config.resolve.alias }), // TODO: resolve.alias per environment?
])
aliasOnlyPluginContainerMap.set(environment, pluginContainer)
Expand Down
7 changes: 1 addition & 6 deletions packages/vite/src/node/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,12 +96,7 @@ export type {
SSROptions,
SSRTarget,
} from './ssr'
export type {
IsolatedPlugin,
IsolatedPluginConstructor,
Plugin,
HookHandler,
} from './plugin'
export type { EnvironmentPlugin, Plugin, HookHandler } from './plugin'
export type {
Logger,
LogOptions,
Expand Down
16 changes: 8 additions & 8 deletions packages/vite/src/node/optimizer/scan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,9 @@ import {
virtualModulePrefix,
virtualModuleRE,
} from '../utils'
import { resolveIsolatedPlugins } from '../plugin'
import type { IsolatedPluginContainer } from '../server/pluginContainer'
import { createIsolatedPluginContainer } from '../server/pluginContainer'
import { resolveEnvironmentPlugins } from '../plugin'
import type { EnvironmentPluginContainer } from '../server/pluginContainer'
import { createEnvironmentPluginContainer } from '../server/pluginContainer'
import { Environment } from '../environment'
import type { DevEnvironment } from '../server/environment'
import { transformGlobImport } from '../plugins/importMetaGlob'
Expand All @@ -47,7 +47,7 @@ import { loadTsconfigJsonForFile } from '../plugins/esbuild'
export class ScanEnvironment extends Environment {
mode = 'scan' as const

get pluginContainer(): IsolatedPluginContainer {
get pluginContainer(): EnvironmentPluginContainer {
if (!this._pluginContainer)
throw new Error(
`${this.name} environment.pluginContainer called before initialized`,
Expand All @@ -57,15 +57,15 @@ export class ScanEnvironment extends Environment {
/**
* @internal
*/
_pluginContainer: IsolatedPluginContainer | undefined
_pluginContainer: EnvironmentPluginContainer | undefined

async init(): Promise<void> {
if (this._inited) {
return
}
this._inited = true
this._plugins = await resolveIsolatedPlugins(this)
this._pluginContainer = await createIsolatedPluginContainer(
this._plugins = await resolveEnvironmentPlugins(this)
this._pluginContainer = await createEnvironmentPluginContainer(
this,
this.plugins,
)
Expand Down Expand Up @@ -101,7 +101,7 @@ export function devToScanEnvironment(
}

type ResolveIdOptions = Omit<
Parameters<IsolatedPluginContainer['resolveId']>[2],
Parameters<EnvironmentPluginContainer['resolveId']>[2],
'environment'
>

Expand Down
Loading

0 comments on commit 54c219e

Please sign in to comment.