Skip to content

Commit

Permalink
fix: remove enforce inside IsolatedPlugins
Browse files Browse the repository at this point in the history
  • Loading branch information
patak-dev committed May 20, 2024
1 parent 0b3cf69 commit a5efd56
Show file tree
Hide file tree
Showing 8 changed files with 84 additions and 83 deletions.
22 changes: 13 additions & 9 deletions packages/vite/src/node/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -534,7 +534,9 @@ export async function build(
function resolveConfigToBuild(
inlineConfig: InlineConfig = {},
patchConfig?: (config: ResolvedConfig) => void,
patchPlugins?: (rawPlugins: (Plugin | IsolatedPluginConstructor)[]) => void,
patchPlugins?: (
resolvedPlugins: (Plugin | IsolatedPluginConstructor)[],
) => void,
) {
return resolveConfig(
inlineConfig,
Expand All @@ -548,7 +550,7 @@ function resolveConfigToBuild(
}

/**
* Build an App environment, or a App library (if librayOptions is provided)
* Build an App environment, or a App library (if libraryOptions is provided)
**/
export async function buildEnvironment(
config: ResolvedConfig,
Expand Down Expand Up @@ -608,9 +610,11 @@ export async function buildEnvironment(

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

const rollupOptions: RollupOptions = {
preserveEntrySignatures: ssr
Expand Down Expand Up @@ -1526,14 +1530,14 @@ export async function createBuilder(
}
}
const patchPlugins = (
rawPlugins: (Plugin | IsolatedPluginConstructor)[],
resolvedPlugins: (Plugin | IsolatedPluginConstructor)[],
) => {
// Force opt-in shared plugins
const environmentPlugins = [...rawPlugins]
const environmentPlugins = [...resolvedPlugins]
let validMixedPlugins = true
for (let i = 0; i < environmentPlugins.length; i++) {
const environmentPlugin = environmentPlugins[i]
const sharedPlugin = config.rawPlugins[i]
const sharedPlugin = config.plugins[i]
if (
config.builder.sharedPlugins ||
environmentPlugin.sharedDuringBuild
Expand All @@ -1547,7 +1551,7 @@ export async function createBuilder(
}
if (validMixedPlugins) {
for (let i = 0; i < environmentPlugins.length; i++) {
rawPlugins[i] = environmentPlugins[i]
resolvedPlugins[i] = environmentPlugins[i]
}
}
}
Expand Down
54 changes: 27 additions & 27 deletions packages/vite/src/node/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,9 @@ import {
import { getFsUtils } from './fsUtils'
import {
createPluginHookUtils,
createResolvePlugins,
getHookHandler,
getSortedPluginsByHook,
resolvePlugins,
} from './plugins'
import type { ESBuildOptions } from './plugins/esbuild'
import type { InternalResolveOptions, ResolveOptions } from './plugins/resolve'
Expand Down Expand Up @@ -538,14 +538,7 @@ export type ResolvedConfig = Readonly<
resolve: Required<ResolveOptions> & {
alias: Alias[]
}
plugins: readonly Plugin[]
rawPlugins: readonly (Plugin | IsolatedPluginConstructor)[]
/** @internal inject user plugins into the shared vite pipeline */
resolvePlugins: (
prePlugins: Plugin[],
normalPlugins: Plugin[],
postPlugins: Plugin[],
) => Plugin[]
plugins: readonly (Plugin | IsolatedPluginConstructor)[]
css: ResolvedCSSOptions
esbuild: ESBuildOptions | false
server: ResolvedServerOptions
Expand Down Expand Up @@ -770,7 +763,7 @@ export async function resolveConfig(
isPreview = false,
patchConfig: ((config: ResolvedConfig) => void) | undefined = undefined,
patchPlugins:
| ((plugins: (Plugin | IsolatedPluginConstructor)[]) => void)
| ((resolvedPlugins: (Plugin | IsolatedPluginConstructor)[]) => void)
| undefined = undefined,
): Promise<ResolvedConfig> {
let config = inlineConfig
Expand Down Expand Up @@ -832,9 +825,6 @@ export async function resolveConfig(
)[]
).filter(filterPlugin)

// Backward compatibility hook used in builder, opt-in to shared plugins during build
patchPlugins?.(rawPlugins)

const sharedPlugins = rawPlugins.filter(
(plugin) => typeof plugin !== 'function',
) as Plugin[]
Expand All @@ -855,7 +845,7 @@ export async function resolveConfig(
// There is no perf hit, because the optimizer is initialized only if ssrLoadModule
// is called.
// During build, we only build the ssr environment if it is configured
// through the deprecated ssr top level options or if it is explicitely defined
// through the deprecated ssr top level options or if it is explicitly defined
// in the environments config
config.environments = { ssr: {}, ...config.environments }
}
Expand Down Expand Up @@ -1139,12 +1129,12 @@ export async function resolveConfig(
mainConfig: resolved,
bundleChain,
}
const resolveWorkerPlugins = await createResolvePlugins(workerResolved)
const resolvedWorkerPlugins = resolveWorkerPlugins(
const resolvedWorkerPlugins = (await resolvePlugins(
workerResolved,
workerPrePlugins,
workerNormalPlugins,
workerPostPlugins,
)
)) as Plugin[] // TODO: worker plugins and isolated constructor

// run configResolved hooks
await Promise.all(
Expand Down Expand Up @@ -1180,8 +1170,6 @@ export async function resolveConfig(
bundleChain: [],
isProduction,
plugins: userPlugins, // placeholder to be replaced
rawPlugins,
resolvePlugins: null as any, // placeholder to be replaced
css: resolveCSSOptions(config.css),
esbuild:
config.esbuild === false
Expand Down Expand Up @@ -1312,21 +1300,33 @@ export async function resolveConfig(
}

// Backward compatibility hook, modify the resolved config before it is used
// to create inernal plugins. For example, `config.build.ssr`. Once we rework
// to create internal plugins. For example, `config.build.ssr`. Once we rework
// internal plugins to use environment.options, we can remove the dual
// patchConfig/patchPlugins and have a single patchConfig before configResolved
// gets called
patchConfig?.(resolved)

const resolvePlugins = await createResolvePlugins(resolved)

;(resolved.resolvePlugins as any) = resolvePlugins

const resolvedPlugins = resolvePlugins(prePlugins, normalPlugins, postPlugins)
const resolvedPlugins = await resolvePlugins(
resolved,
prePlugins,
normalPlugins,
postPlugins,
)

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

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

// call configResolved hooks
await Promise.all(
Expand Down
11 changes: 5 additions & 6 deletions packages/vite/src/node/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import type {
ResolvedConfig,
UserConfig,
} from './config'
import { sortUserPlugins } from './config'
import type { ServerHook, ViteDevServer } from './server'
import type { IndexHtmlTransform } from './plugins/html'
import type { EnvironmentModuleNode } from './server/moduleGraph'
Expand Down Expand Up @@ -355,22 +354,22 @@ export type PluginOption =
export async function resolveIsolatedPlugins(
environment: PluginEnvironment,
): Promise<IsolatedPlugin[]> {
const userPlugins: IsolatedPlugin[] = []
for (const plugin of environment.config.rawPlugins) {
const resolvedPlugins: IsolatedPlugin[] = []
for (const plugin of environment.config.plugins) {
if (typeof plugin === 'function') {
const isolatedPlugin = await plugin(environment)
if (isolatedPlugin) {
const flatPlugins = await asyncFlattenIsolatedPlugin(
environment,
isolatedPlugin,
)
userPlugins.push(...flatPlugins)
resolvedPlugins.push(...flatPlugins)
}
} else {
userPlugins.push(plugin)
resolvedPlugins.push(plugin)
}
}
return environment.config.resolvePlugins(...sortUserPlugins(userPlugins))
return resolvedPlugins
}

async function asyncFlattenIsolatedPlugin(
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/plugins/html.ts
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,7 @@ function handleParseError(
*/
export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
const [preHooks, normalHooks, postHooks] = resolveHtmlTransforms(
config.plugins,
config.plugins.filter((plugin) => typeof plugin !== 'function') as Plugin[],
config.logger,
)
preHooks.unshift(injectCspNonceMetaTagHook(config))
Expand Down
54 changes: 23 additions & 31 deletions packages/vite/src/node/plugins/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@ import aliasPlugin, { type ResolverFunction } from '@rollup/plugin-alias'
import type { ObjectHook } from 'rollup'
import type { PluginHookUtils, ResolvedConfig } from '../config'
import { isDepsOptimizerEnabled } from '../config'
import type { HookHandler, Plugin, PluginWithRequiredHook } from '../plugin'
import type {
HookHandler,
IsolatedPluginConstructor,
Plugin,
PluginWithRequiredHook,
} from '../plugin'
import { watchPackageDataPlugin } from '../packages'
import { getFsUtils } from '../fsUtils'
import { jsonPlugin } from './json'
Expand All @@ -26,15 +31,12 @@ import { dynamicImportVarsPlugin } from './dynamicImportVars'
import { importGlobPlugin } from './importMetaGlob'
// TODO: import { loadFallbackPlugin } from './loadFallback'

export async function createResolvePlugins(
export async function resolvePlugins(
config: ResolvedConfig,
): Promise<
(
prePlugins: Plugin[],
normalPlugins: Plugin[],
postPlugins: Plugin[],
) => Plugin[]
> {
prePlugins: Plugin[],
normalPlugins: Plugin[],
postPlugins: Plugin[],
): Promise<(Plugin | IsolatedPluginConstructor)[]> {
const isBuild = config.command === 'build'
const isWorker = config.isWorker
const buildPlugins = isBuild
Expand All @@ -46,7 +48,7 @@ export async function createResolvePlugins(
(isDepsOptimizerEnabled(config, false) ||
isDepsOptimizerEnabled(config, true))

const preVitePlugins = [
return [
depsOptimizerEnabled ? optimizedDepsPlugin(config) : null,
isBuild ? metadataPlugin() : null,
!isWorker ? watchPackageDataPlugin(config.packageCache) : null,
Expand All @@ -55,9 +57,9 @@ export async function createResolvePlugins(
entries: config.resolve.alias,
customResolver: viteAliasCustomResolver,
}),
]
// then ...prePlugins
const normalVitePlugins = [

...prePlugins,

modulePreload !== false && modulePreload.polyfill
? modulePreloadPolyfillPlugin(config)
: null,
Expand Down Expand Up @@ -87,9 +89,9 @@ export async function createResolvePlugins(
wasmHelperPlugin(config),
webWorkerPlugin(config),
assetPlugin(config),
]
// then ...normalPlugins
const postVitePlugins = [

...normalPlugins,

wasmFallbackPlugin(),
definePlugin(config),
cssPostPlugin(config),
Expand All @@ -99,10 +101,11 @@ export async function createResolvePlugins(
...buildPlugins.pre,
dynamicImportVarsPlugin(config),
importGlobPlugin(config),
]
// then ...postVitePlugins
const finalVitePlugins = [

...postPlugins,

...buildPlugins.post,

// internal server-only plugins are always applied after everything else
...(isBuild
? []
Expand All @@ -112,18 +115,7 @@ export async function createResolvePlugins(
importAnalysisPlugin(config),
// TODO: loadFallbackPlugin(config),
]),
]
return (prePlugins, normalPlugins, postPlugins) => {
return [
...preVitePlugins,
...prePlugins,
...normalVitePlugins,
...normalPlugins,
...postVitePlugins,
...postPlugins,
...finalVitePlugins,
].filter(Boolean) as Plugin[]
}
].filter(Boolean) as (Plugin | IsolatedPluginConstructor)[]
}

export function createPluginHookUtils(
Expand Down
6 changes: 5 additions & 1 deletion packages/vite/src/node/preview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { indexHtmlMiddleware } from './server/middlewares/indexHtml'
import { notFoundMiddleware } from './server/middlewares/notFound'
import { proxyMiddleware } from './server/middlewares/proxy'
import { resolveHostname, resolveServerUrls, shouldServeFile } from './utils'
import type { Plugin } from './plugin'
import { printServerUrls } from './logger'
import { bindCLIShortcuts } from './shortcuts'
import type { BindCLIShortcutsOptions } from './shortcuts'
Expand Down Expand Up @@ -114,10 +115,13 @@ export async function preview(
const clientOutDir =
config.environments.client.build.outDir ?? config.build.outDir
const distDir = path.resolve(config.root, clientOutDir)
const plugins = config.plugins.filter(
(plugin) => typeof plugin !== 'function',
) as Plugin[]
if (
!fs.existsSync(distDir) &&
// error if no plugins implement `configurePreviewServer`
config.plugins.every((plugin) => !plugin.configurePreviewServer) &&
plugins.every((plugin) => !plugin.configurePreviewServer) &&
// error if called in CLI only. programmatic usage could access `httpServer`
// and affect file serving
process.argv[1]?.endsWith(path.normalize('bin/vite.js')) &&
Expand Down
14 changes: 7 additions & 7 deletions packages/vite/src/node/server/hmr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import colors from 'picocolors'
import type { CustomPayload, HMRPayload, Update } from 'types/hmrPayload'
import type { RollupError } from 'rollup'
import { CLIENT_DIR } from '../constants'
import type { ResolvedConfig } from '../config'
import type { Environment } from '../environment'
import { createDebugger, normalizePath } from '../utils'
import type { InferCustomEventPayload, ViteDevServer } from '..'
import { getHookHandler } from '../plugins'
Expand Down Expand Up @@ -165,12 +165,12 @@ export function getSortedPluginsByHotUpdateHook(
return sortedPlugins
}

const sortedHotUpdatePluginsCache = new WeakMap<ResolvedConfig, Plugin[]>()
function getSortedHotUpdatePlugins(config: ResolvedConfig): Plugin[] {
let sortedPlugins = sortedHotUpdatePluginsCache.get(config) as Plugin[]
const sortedHotUpdatePluginsCache = new WeakMap<Environment, Plugin[]>()
function getSortedHotUpdatePlugins(environment: Environment): Plugin[] {
let sortedPlugins = sortedHotUpdatePluginsCache.get(environment) as Plugin[]
if (!sortedPlugins) {
sortedPlugins = getSortedPluginsByHotUpdateHook(config.plugins)
sortedHotUpdatePluginsCache.set(config, sortedPlugins)
sortedPlugins = getSortedPluginsByHotUpdateHook(environment.plugins)
sortedHotUpdatePluginsCache.set(environment, sortedPlugins)
}
return sortedPlugins
}
Expand Down Expand Up @@ -255,7 +255,7 @@ export async function handleHMRUpdate(

let hmrContext

for (const plugin of getSortedHotUpdatePlugins(config)) {
for (const plugin of getSortedHotUpdatePlugins(environment)) {
if (plugin.hotUpdate) {
const filteredModules = await getHookHandler(plugin.hotUpdate)(
hotContext,
Expand Down
Loading

0 comments on commit a5efd56

Please sign in to comment.