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

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
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
})
})
19 changes: 16 additions & 3 deletions packages/vite/src/node/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ import {
mergeWithDefaults,
normalizePath,
partialEncodeURIPath,
rollupVersion,
} from './utils'
import { perEnvironmentPlugin, resolveEnvironmentPlugins } from './plugin'
import { manifestPlugin } from './plugins/manifest'
Expand All @@ -77,8 +78,9 @@ import {
BaseEnvironment,
getDefaultResolvedEnvironmentOptions,
} from './baseEnvironment'
import type { Plugin } from './plugin'
import type { MinimalPluginContextWithoutEnvironment, Plugin } from './plugin'
import type { RollupPluginHooks } from './typeUtils'
import { BasicMinimalPluginContext } from './server/pluginContainer'

export interface BuildEnvironmentOptions {
/**
Expand Down Expand Up @@ -1573,6 +1575,14 @@ export async function createBuilder(
environments,
config,
async buildApp() {
const pluginContext = new BasicMinimalPluginContext(
{
rollupVersion,
watchMode: false,
},
config.logger,
)

// order 'pre' and 'normal' hooks are run first, then config.builder.buildApp, then 'post' hooks
let configBuilderBuildAppCalled = false
for (const p of config.getSortedPlugins('buildApp')) {
Expand All @@ -1586,7 +1596,7 @@ export async function createBuilder(
await configBuilder.buildApp(builder)
}
const handler = getHookHandler(hook)
await handler(builder)
await handler.call(pluginContext, builder)
}
if (!configBuilderBuildAppCalled) {
await configBuilder.buildApp(builder)
Expand Down Expand Up @@ -1670,4 +1680,7 @@ export async function createBuilder(
return builder
}

export type BuildAppHook = (this: void, builder: ViteBuilder) => Promise<void>
export type BuildAppHook = (
this: MinimalPluginContextWithoutEnvironment,
builder: ViteBuilder,
) => Promise<void>
Loading