Skip to content

Commit

Permalink
chore: require "connection" event, use rserver.hot instead of server.ws
Browse files Browse the repository at this point in the history
  • Loading branch information
sheremet-va committed Dec 29, 2023
1 parent d1f515f commit 72d6c4d
Show file tree
Hide file tree
Showing 5 changed files with 15 additions and 17 deletions.
16 changes: 7 additions & 9 deletions docs/guide/api-plugin.md
Original file line number Diff line number Diff line change
Expand Up @@ -423,11 +423,11 @@ Vite plugins can also provide hooks that serve Vite-specific purposes. These hoo

- Filter and narrow down the affected module list so that the HMR is more accurate.

- Return an empty array and perform complete custom HMR handling by sending custom events to the client:
- Return an empty array and perform complete custom HMR handling by sending custom events to the client (example uses `server.hot` which was introduced in Vite #, it is recommended to also use `server.ws` if you support lower versions):

```js
handleHotUpdate({ server }) {
server.ws.send({
server.hot.send({
type: 'custom',
event: 'special-update',
data: {}
Expand Down Expand Up @@ -534,9 +534,7 @@ Since Vite 2.9, we provide some utilities for plugins to help handle the communi

### Server to Client

<!-- TODO: add server.hot.on docs -->

On the plugin side, we could use `server.ws.send` to broadcast events to all the clients:
On the plugin side, we could use `server.hot.send` (since Vite #) or `server.ws.send` to broadcast events to all the clients:

```js
// vite.config.js
Expand All @@ -546,8 +544,8 @@ export default defineConfig({
// ...
configureServer(server) {
// Example: wait for a client to connect before sending a message
server.ws.on('connection', () => {
server.ws.send('my:greetings', { msg: 'hello' })
server.hot.on('connection', () => {
server.hot.send('my:greetings', { msg: 'hello' })
})
},
},
Expand Down Expand Up @@ -581,7 +579,7 @@ if (import.meta.hot) {
}
```

Then use `server.ws.on` and listen to the events on the server side:
Then use `server.hot.on` (since Vite #) or `server.ws.on` and listen to the events on the server side:

```js
// vite.config.js
Expand All @@ -590,7 +588,7 @@ export default defineConfig({
{
// ...
configureServer(server) {
server.ws.on('my:from-client', (data, client) => {
server.hot.on('my:from-client', (data, client) => {
console.log('Message from client:', data.msg) // Hey!
// reply only to the client (if needed)
client.send('my:ack', { msg: 'Hi! I got your message!' })
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ export interface Plugin<A = any> extends RollupPlugin<A> {
* the descriptors.
*
* - The hook can also return an empty array and then perform custom updates
* by sending a custom hmr payload via server.ws.send().
* by sending a custom hmr payload via server.hot.send().
*
* - If the hook doesn't return a value, the hmr update will be performed as
* normal.
Expand Down
3 changes: 2 additions & 1 deletion packages/vite/src/node/server/hmr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ export interface HMRChannel {
...args: any[]
) => void,
): void
on(event: 'connection', listener: () => void): void
/**
* Unregister event listener.
*/
Expand Down Expand Up @@ -686,7 +687,7 @@ export function createHMRBroadcaster(): HMRBroadcaster {
addChannel(channel) {
channels.push(channel)
},
on(event, listener) {
on(event: string, listener: (...args: any[]) => any) {
channels.forEach((channel) => channel.on(event, listener))
return broadcaster
},
Expand Down
3 changes: 1 addition & 2 deletions packages/vite/src/node/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import launchEditorMiddleware from 'launch-editor-middleware'
import type { SourceMap } from 'rollup'
import picomatch from 'picomatch'
import type { Matcher } from 'picomatch'
import type { InvalidatePayload } from 'types/customEvent'
import type { CommonServerOptions } from '../http'
import {
httpServerStart,
Expand Down Expand Up @@ -696,7 +695,7 @@ export async function _createServer(
onFileAddUnlink(file, true)
})

ws.on('vite:invalidate', async ({ path, message }: InvalidatePayload) => {
hot.on('vite:invalidate', async ({ path, message }) => {
const mod = moduleGraph.urlToModuleMap.get(path)
if (mod && mod.isSelfAccepting && mod.lastHMRTimestamp > 0) {
config.logger.info(
Expand Down
8 changes: 4 additions & 4 deletions playground/hmr/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@ export default defineConfig({
if (file.endsWith('customFile.js')) {
const content = await read()
const msg = content.match(/export const msg = '(\w+)'/)[1]
server.ws.send('custom:foo', { msg })
server.ws.send('custom:remove', { msg })
server.hot.send('custom:foo', { msg })
server.hot.send('custom:remove', { msg })
}
},
configureServer(server) {
server.ws.on('custom:remote-add', ({ a, b }, client) => {
server.hot.on('custom:remote-add', ({ a, b }, client) => {
client.send('custom:remote-add-result', { result: a + b })
})
},
Expand All @@ -44,7 +44,7 @@ export const virtual = _virtual + '${num}';`
}
},
configureServer(server) {
server.ws.on('virtual:increment', async () => {
server.hot.on('virtual:increment', async () => {
const mod = await server.moduleGraph.getModuleByUrl('\0virtual:file')
if (mod) {
num++
Expand Down

0 comments on commit 72d6c4d

Please sign in to comment.