Skip to content

feat: make PluginContext available for Vite-specific hooks #19936

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
279 changes: 279 additions & 0 deletions packages/vite/src/node/__tests__/plugins/hooks.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,279 @@
import path from 'node:path'
import { describe, expect, onTestFinished, test } from 'vitest'
import { build } from '../../build'
import type { Plugin } from '../../plugin'
import { resolveConfig } from '../../config'
import { createServer } from '../../server'
import { preview } from '../../preview'
import { promiseWithResolvers } from '../../../shared/utils'

const resolveConfigWithPlugin = (
plugin: Plugin,
command: 'serve' | 'build' = 'serve',
) => {
return resolveConfig(
{ configFile: false, plugins: [plugin], logLevel: 'error' },
command,
)
}

const createServerWithPlugin = async (plugin: Plugin) => {
const server = await createServer({
configFile: false,
root: import.meta.dirname,
plugins: [plugin],
logLevel: 'error',
server: {
middlewareMode: true,
},
})
onTestFinished(() => server.close())
return server
}

const createPreviewServerWithPlugin = async (plugin: Plugin) => {
const server = await preview({
configFile: false,
root: import.meta.dirname,
plugins: [
{
name: 'mock-preview',
configurePreviewServer({ httpServer }) {
// NOTE: make httpServer.listen no-op to avoid starting a server
httpServer.listen = (...args: unknown[]) => {
const listener = args.at(-1) as () => void
listener()
return httpServer as any
}
},
},
plugin,
],
logLevel: 'error',
})
onTestFinished(() => server.close())
return server
}

const buildWithPlugin = async (plugin: Plugin) => {
await build({
root: path.resolve(import.meta.dirname, '../packages/build-project'),
logLevel: 'error',
build: {
write: false,
},
plugins: [
{
name: 'resolve-entry.js',
resolveId(id) {
if (id === 'entry.js') {
return '\0' + id
}
},
load(id) {
if (id === '\0entry.js') {
return 'export default {}'
}
},
},
plugin,
],
})
}

describe('supports plugin context', () => {
test('config hook', async () => {
expect.assertions(3)

await resolveConfigWithPlugin({
name: 'test',
config() {
expect(this).toMatchObject({
debug: expect.any(Function),
info: expect.any(Function),
warn: expect.any(Function),
error: expect.any(Function),
meta: expect.any(Object),
})
expect(this.meta.rollupVersion).toBeTypeOf('string')
// @ts-expect-error watchMode should not exist in types
expect(this.meta.watchMode).toBeUndefined()
},
})
})

test('configEnvironment hook', async () => {
expect.assertions(3)

await resolveConfigWithPlugin({
name: 'test',
configEnvironment(name) {
if (name !== 'client') return

expect(this).toMatchObject({
debug: expect.any(Function),
info: expect.any(Function),
warn: expect.any(Function),
error: expect.any(Function),
meta: expect.any(Object),
})
expect(this.meta.rollupVersion).toBeTypeOf('string')
// @ts-expect-error watchMode should not exist in types
expect(this.meta.watchMode).toBeUndefined()
},
})
})

test('configResolved hook', async () => {
expect.assertions(3)

await resolveConfigWithPlugin({
name: 'test',
configResolved() {
expect(this).toMatchObject({
debug: expect.any(Function),
info: expect.any(Function),
warn: expect.any(Function),
error: expect.any(Function),
meta: expect.any(Object),
})
expect(this.meta.rollupVersion).toBeTypeOf('string')
expect(this.meta.watchMode).toBe(true)
},
})
})

test('configureServer hook', async () => {
expect.assertions(3)

await createServerWithPlugin({
name: 'test',
configureServer() {
expect(this).toMatchObject({
debug: expect.any(Function),
info: expect.any(Function),
warn: expect.any(Function),
error: expect.any(Function),
meta: expect.any(Object),
})
expect(this.meta.rollupVersion).toBeTypeOf('string')
expect(this.meta.watchMode).toBe(true)
},
})
})

test('configurePreviewServer hook', async () => {
expect.assertions(3)

await createPreviewServerWithPlugin({
name: 'test',
configurePreviewServer() {
expect(this).toMatchObject({
debug: expect.any(Function),
info: expect.any(Function),
warn: expect.any(Function),
error: expect.any(Function),
meta: expect.any(Object),
})
expect(this.meta.rollupVersion).toBeTypeOf('string')
expect(this.meta.watchMode).toBe(false)
},
})
})

test('transformIndexHtml hook in dev', async () => {
expect.assertions(3)

const server = await createServerWithPlugin({
name: 'test',
transformIndexHtml() {
expect(this).toMatchObject({
debug: expect.any(Function),
info: expect.any(Function),
warn: expect.any(Function),
error: expect.any(Function),
meta: expect.any(Object),
})
expect(this.meta.rollupVersion).toBeTypeOf('string')
expect(this.meta.watchMode).toBe(true)
},
})
await server.transformIndexHtml('/index.html', '<html></html>')
})

test('transformIndexHtml hook in build', async () => {
expect.assertions(3)

await buildWithPlugin({
name: 'test',
transformIndexHtml() {
expect(this).toMatchObject({
debug: expect.any(Function),
info: expect.any(Function),
warn: expect.any(Function),
error: expect.any(Function),
meta: expect.any(Object),
})
expect(this.meta.rollupVersion).toBeTypeOf('string')
expect(this.meta.watchMode).toBe(false)
},
})
})

test('handleHotUpdate hook', async () => {
expect.assertions(3)

const { promise, resolve } = promiseWithResolvers<void>()
const server = await createServerWithPlugin({
name: 'test',
handleHotUpdate() {
expect(this).toMatchObject({
debug: expect.any(Function),
info: expect.any(Function),
warn: expect.any(Function),
error: expect.any(Function),
meta: expect.any(Object),
})
expect(this.meta.rollupVersion).toBeTypeOf('string')
expect(this.meta.watchMode).toBe(true)
resolve()
},
})
server.watcher.emit(
'change',
path.resolve(import.meta.dirname, 'index.html'),
)

await promise
})

test('hotUpdate hook', async () => {
expect.assertions(3)

const { promise, resolve } = promiseWithResolvers<void>()
const server = await createServerWithPlugin({
name: 'test',
hotUpdate() {
if (this.environment.name !== 'client') return

expect(this).toMatchObject({
debug: expect.any(Function),
info: expect.any(Function),
warn: expect.any(Function),
error: expect.any(Function),
meta: expect.any(Object),
environment: expect.any(Object),
})
expect(this.meta.rollupVersion).toBeTypeOf('string')
expect(this.meta.watchMode).toBe(true)
resolve()
},
})
server.watcher.emit(
'change',
path.resolve(import.meta.dirname, 'index.html'),
)

await promise
})
})
36 changes: 31 additions & 5 deletions packages/vite/src/node/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { createRequire } from 'node:module'
import crypto from 'node:crypto'
import colors from 'picocolors'
import type { Alias, AliasOptions } from 'dep-types/alias'
import type { RollupOptions } from 'rollup'
import type { PluginContextMeta, RollupOptions } from 'rollup'
import picomatch from 'picomatch'
import { build } from 'esbuild'
import type { AnymatchFn } from '../types/anymatch'
Expand Down Expand Up @@ -76,6 +76,7 @@ import {
nodeLikeBuiltins,
normalizeAlias,
normalizePath,
rollupVersion,
} from './utils'
import {
createPluginHookUtils,
Expand Down Expand Up @@ -103,6 +104,7 @@ import { PartialEnvironment } from './baseEnvironment'
import { createIdResolver } from './idResolver'
import { runnerImport } from './ssr/runnerImport'
import { getAdditionalAllowedHosts } from './server/middlewares/hostCheck'
import { BasicMinimalPluginContext } from './server/pluginContainer'

const debug = createDebugger('vite:config', { depth: 10 })
const promisifiedRealpath = promisify(fs.realpath)
Expand Down Expand Up @@ -1224,6 +1226,7 @@ export async function resolveConfig(
await runConfigEnvironmentHook(
config.environments,
userPlugins,
logger,
configEnv,
config.ssr?.target === 'webworker',
)
Expand Down Expand Up @@ -1365,6 +1368,16 @@ export async function resolveConfig(

const BASE_URL = resolvedBase

const resolvedConfigContext = new BasicMinimalPluginContext(
{
rollupVersion,
watchMode:
(command === 'serve' && !isPreview) ||
(command === 'build' && !!resolvedBuildOptions.watch),
} satisfies PluginContextMeta,
logger,
)

let resolved: ResolvedConfig

let createUserWorkerPlugins = config.worker?.plugins
Expand Down Expand Up @@ -1423,7 +1436,7 @@ export async function resolveConfig(
await Promise.all(
createPluginHookUtils(resolvedWorkerPlugins)
.getSortedPluginHooks('configResolved')
.map((hook) => hook(workerResolved)),
.map((hook) => hook.call(resolvedConfigContext, workerResolved)),
)

return {
Expand Down Expand Up @@ -1583,7 +1596,7 @@ export async function resolveConfig(
await Promise.all(
resolved
.getSortedPluginHooks('configResolved')
.map((hook) => hook(resolved)),
.map((hook) => hook.call(resolvedConfigContext, resolved)),
)

optimizeDepsDisabledBackwardCompatibility(resolved, resolved.optimizeDeps)
Expand Down Expand Up @@ -2082,10 +2095,18 @@ async function runConfigHook(
): Promise<InlineConfig> {
let conf = config

const tempLogger = createLogger(config.logLevel, {
allowClearScreen: config.clearScreen,
customLogger: config.customLogger,
})
const context = new BasicMinimalPluginContext<
Omit<PluginContextMeta, 'watchMode'>
>({ rollupVersion }, tempLogger)

for (const p of getSortedPluginsByHook('config', plugins)) {
const hook = p.config
const handler = getHookHandler(hook)
const res = await handler(conf, configEnv)
const res = await handler.call(context, conf, configEnv)
if (res && res !== conf) {
conf = mergeConfig(conf, res)
}
Expand All @@ -2097,15 +2118,20 @@ async function runConfigHook(
async function runConfigEnvironmentHook(
environments: Record<string, EnvironmentOptions>,
plugins: Plugin[],
logger: Logger,
configEnv: ConfigEnv,
isSsrTargetWebworkerSet: boolean,
): Promise<void> {
const context = new BasicMinimalPluginContext<
Omit<PluginContextMeta, 'watchMode'>
>({ rollupVersion }, logger)

const environmentNames = Object.keys(environments)
for (const p of getSortedPluginsByHook('configEnvironment', plugins)) {
const hook = p.configEnvironment
const handler = getHookHandler(hook)
for (const name of environmentNames) {
const res = await handler(name, environments[name], {
const res = await handler.call(context, name, environments[name], {
...configEnv,
isSsrTargetWebworker: isSsrTargetWebworkerSet && name === 'ssr',
})
Expand Down
Loading