oven-sh / bun

Incredibly fast JavaScript runtime, bundler, test runner, and package manager – all in one
https://bun.sh
Other
74.24k stars 2.77k forks source link

How to use `vite.createServer` with `Bun.serve`? #12212

Open Blankeos opened 4 months ago

Blankeos commented 4 months ago

What is the problem this feature would solve?

Since Bun.serve doesn't have http.Incoming and http.ServerResponse, I'm wondering how to implement an equivalent of this Node code in Bun.

In Node:

import { Hono } from 'hono'
import { serve, type HttpBindings } from '@hono/node-server'
import type { ViteDevServer } from 'vite'

const base = process.env.BASE || '/'

const app = new Hono<{ Bindings: HttpBindings }>()

let vite: ViteDevServer
if (!isProduction) {
    const { createServer } = await import('vite')
    vite = await createServer({
        server: { middlewareMode: true },
        appType: 'custom',
        base
    })
    app.use(async (c, next) => {
        const viteDevMiddleware = () => new Promise<void>((resolve) => {
            vite.middlewares(c.env.incoming, c.env.outgoing, () => resolve())
        });
        await viteDevMiddleware()
        await next()
    })
}

serve({
    fetch: app.fetch,
    port
});

What is the feature you are proposing to solve the problem?

Maybe an adapter for Bun.serve with http.Incoming and http.ServerResponse if it's possible?

What alternatives have you considered?

No response

huseeiin commented 4 months ago

this is not an issue in bun. you cannot use connect middleware directly with Bun.serve. you should use express or polka or fastify with @fastify/middie

Blankeos commented 3 months ago

After some experimenting, this one actually works: https://github.com/vikejs/vike-node/blob/main/packages/vike-node/src/runtime/adapters/connectToWeb.ts

it's by @nitedani. Here's my current code with working Bun + Vite HMR + Custom Websocket handler + Watching of backend changes (like in controllers).

Only caveats I noticed (reproducible in the above example):