Skip to content
Draft
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
52 changes: 52 additions & 0 deletions docs/guide/api-plugin.md
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,58 @@ Vite plugins can also provide hooks that serve Vite-specific purposes. These hoo
})
```

### `closeServer`

- **Type:** `(context: { reason: 'restart' | 'close' }) => void | Promise<void>`
- **Kind:** `async`, `parallel`
- **Scope:** [Global](/guide/api-environment-plugins#per-environment-hooks-and-global-hooks)

Called when the dev server is restarted or closed, after the server has been torn down. Typically used to dispose resources created in [`configureServer`](/guide/api-plugin.html#configureserver).

The `context.reason` distinguishes the two cases:
- `'restart'` — the server is restarting (e.g. a config file change or a call to `server.restart()`).
- `'close'` — the server is shutting down (e.g. the `q` shortcut, `SIGTERM`, a forced exit such as `Ctrl+C`, or a call to `server.close()`).

```js
const myPlugin = () => {
let resource
return {
name: 'close-server',
configureServer(server) {
resource = createResource()
},
async closeServer({ reason }) {
if (reason === 'close') {
await resource.dispose()
}
},
}
}
```

### `closePreviewServer`

- **Type:** `() => void | Promise<void>`
- **Kind:** `async`, `parallel`
- **Scope:** [Global](/guide/api-environment-plugins#per-environment-hooks-and-global-hooks)

Same as [`closeServer`](/guide/api-plugin.html#closeserver) but for the preview server. The preview server never restarts, so there is no `reason`.

```js
const myPlugin = () => {
let resource
return {
name: 'close-preview-server',
configurePreviewServer(server) {
resource = createResource()
},
async closePreviewServer() {
await resource.dispose()
},
}
}
```

### `transformIndexHtml`

- **Type:** `IndexHtmlTransformHook | { order?: 'pre' | 'post', handler: IndexHtmlTransformHook }`
Expand Down
24 changes: 24 additions & 0 deletions packages/vite/LICENSE.md
Original file line number Diff line number Diff line change
Expand Up @@ -2045,6 +2045,30 @@ Repository: http://github.com/ljharb/shell-quote

---------------------------------------

## signal-exit
License: ISC
By: Ben Coe
Repository: https://github.com/tapjs/signal-exit

> The ISC License
>
> Copyright (c) 2015-2023 Benjamin Coe, Isaac Z. Schlueter, and Contributors
>
> Permission to use, copy, modify, and/or distribute this software
> for any purpose with or without fee is hereby granted, provided
> that the above copyright notice and this permission notice
> appear in all copies.
>
> THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
> WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
> OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE
> LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
> OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
> WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
> ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

---------------------------------------

## sirv
License: MIT
By: Luke Edwards
Expand Down
1 change: 1 addition & 0 deletions packages/vite/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@
"rollup-plugin-license": "^3.7.1",
"sass": "^1.102.0",
"sass-embedded": "^1.100.0",
"signal-exit": "^4.1.0",
"sirv": "^3.0.2",
"strip-literal": "^4.0.0",
"terser": "^5.49.0",
Expand Down
166 changes: 166 additions & 0 deletions packages/vite/src/node/__tests__/plugins/hooks.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -446,3 +446,169 @@ describe('watcher add/unlink error handling', () => {
expect(logError).toHaveBeenCalledWith(error)
})
})

describe('closeServer hook', () => {
test('is called with reason "close" on server.close()', async () => {
const closeServer = vi.fn()
const server = await createServerWithPlugin({
name: 'test',
closeServer,
})

await server.close()

expect(closeServer).toHaveBeenCalledTimes(1)
expect(closeServer).toHaveBeenCalledWith({ reason: 'close' })
})

test('receives a minimal plugin context as `this`', async () => {
expect.assertions(2)

const server = await createServerWithPlugin({
name: 'test',
closeServer() {
expect(this).toMatchObject({
debug: expect.any(Function),
info: expect.any(Function),
warn: expect.any(Function),
error: expect.any(Function),
meta: expect.any(Object),
})
// Global hooks don't have an environment.
expect(this).not.toHaveProperty('environment')
},
})

await server.close()
})

test('is awaited before server.close() resolves', async () => {
let hookDone = false
const server = await createServerWithPlugin({
name: 'test',
async closeServer() {
await new Promise((r) => setTimeout(r, 10))
hookDone = true
},
})

await server.close()

// `server.close()` does not resolve until the async hook has completed.
expect(hookDone).toBe(true)
})

test('runs after the server is torn down (after closeBundle)', async () => {
const order: string[] = []
const server = await createServerWithPlugin({
name: 'test',
closeBundle() {
order.push('closeBundle')
},
closeServer() {
order.push('closeServer')
},
})

await server.close()

// `closeBundle` runs as part of teardown (once per environment); the
// `closeServer` hook runs afterwards, so it is the last event.
expect(order.at(-1)).toBe('closeServer')
expect(order.indexOf('closeBundle')).toBeLessThan(
order.indexOf('closeServer'),
)
})

test('runs hooks in parallel', async () => {
const events: string[] = []
const server = await createServer({
configFile: false,
root: import.meta.dirname,
plugins: [
{
name: 'a',
async closeServer() {
events.push('a:start')
await new Promise((r) => setTimeout(r, 20))
events.push('a:end')
},
},
{
name: 'b',
async closeServer() {
events.push('b:start')
await new Promise((r) => setTimeout(r, 20))
events.push('b:end')
},
},
resolveEntryPlugin,
],
logLevel: 'error',
server: { middlewareMode: true, ws: false },
})

await server.close()

// Both hooks start before either finishes.
expect(events.slice(0, 2)).toStrictEqual(['a:start', 'b:start'])
})

test('is called only once even if close() is called multiple times', async () => {
const closeServer = vi.fn()
const server = await createServerWithPlugin({
name: 'test',
closeServer,
})

await Promise.all([server.close(), server.close()])
await server.close()

expect(closeServer).toHaveBeenCalledTimes(1)
})

test('is called with reason "restart" on server.restart()', async () => {
const closeServer = vi.fn()
const server = await createServerWithPlugin({
name: 'test',
closeServer,
})

await server.restart()

expect(closeServer).toHaveBeenCalledTimes(1)
expect(closeServer).toHaveBeenCalledWith({ reason: 'restart' })

await server.close()
})
})

describe('closePreviewServer hook', () => {
test('is called on preview server.close()', async () => {
const closePreviewServer = vi.fn()
const server = await createPreviewServerWithPlugin({
name: 'test',
closePreviewServer,
})

await server.close()

expect(closePreviewServer).toHaveBeenCalledTimes(1)
})

test('is awaited before server.close() resolves', async () => {
let hookDone = false
const server = await createPreviewServerWithPlugin({
name: 'test',
async closePreviewServer() {
await new Promise((r) => setTimeout(r, 10))
hookDone = true
},
})

await server.close()

// `server.close()` does not resolve until the async hook has completed.
expect(hookDone).toBe(true)
})
})
Loading
Loading