vite-plugin-ws
v0.1.0
Published
Vite plugin for websockets.
Readme
vite-plugin-ws
Vite plugin for websockets.
Why?
I found it difficult to properly setup a websocket server with Vite. This plugin allows for easy interaction of websockets with Vite in dev and preview.
Quick start
Install with your package manager:
npm i ws
npm i vite-plugin-ws -D
# for typescript
npm i @types/ws -DUpdate your vite.config.ts:
import { defineConfig } from 'vite';
import ws from 'vite-plugin-ws';
export default defineConfig({
plugins: [
ws({
path: '/ws',
setup(wss) {
wss.on('connection', socket => {
socket.send('Connected!');
});
}
})
]
});You can also create a seperate file e.g.:
// src/ws.ts
import type { WebSocketServer } from 'ws';
export default function setupWebSocket(wss: WebSocketServer) {
// ...
}... and then your config file:
// vite.config.ts
import { defineConfig } from 'vite';
import ws from 'vite-plugin-ws';
import setupWebSocket from './src/ws';
export default defineConfig({
plugins: [
ws({ setup: setupWebSocket })
]
});See an example.
Options
import type { WebSocketServer, ServerOptions } from 'ws';
interface Options {
/**
* Setup WebSocket server.
*
* @example
* ```ts
* setup(wss) {
* wss.on('connection', socket => {
* socket.send('Connected!');
* });
* }
*/
setup(wss: WebSocketServer): void;
/**
* Path to the WebSocket url.
* @default '/ws'
*/
path?: string;
/**
* Options for `ws.ServerOptions`.
*
* @see https://github.com/websockets/ws/blob/master/doc/ws.md#class-websocketserver
*/
wsOptions?: ServerOptions;
}License
MIT 💖
