honojs / vite-plugins

Vite Plugins for Hono
https://hono.dev
134 stars 35 forks source link

When using @hono/vite-dev-server in Cloudflare Workers development, there is a misjudgment in hono/adapter's env(). #103

Closed natsumesou closed 8 months ago

natsumesou commented 9 months ago

When using @hono/vite-dev-server for live reloading settings during local development with Cloudflare Workers, environment variables defined in wrangler.toml are not recognized.

Specifically, if wrangler.toml contains settings like the following:

[vars]
NAME="test"

The following code will recognize the variable:

app.get("/", async (c) => {
    return c.text(c.env.NAME) // => test
}

However, it is not recognized in the env() function of the Adapter Helper.

import { env } from 'hono/adapter'

app.get('/', (c) => {
  const { NAME } = env<{ NAME: string }>(c)
  return c.text(NAME) // => `undefined`(empty response)
})

The cause is that global?.WebSocketPair is undefined for getRuntimeKey() in env() to determine workerd via @hono/vite-dev-server's devServer(), and getRuntimeKey() returns node. cf. https://github.com/honojs/hono/blob/v4.0.8/src/helper/adapter/index.ts#L33-L57

I have made a fix that works locally as a workaround, but since I have no knowledge of Vite, I am not sure if this is the correct approach. Here is my workaround commit: https://github.com/natsumesou/vite-plugins/commit/717b19a0d294606f49b609955c0ed77e264e6804

Please advise if you have any suggestions :) Thank you!

yusukebe commented 9 months ago

Hi @natsumesou !

You are right. That problem can happen.

The best solution is that make adapter can receive a runtime key like workerd. Maybe we can handle it with this approach.

natsumesou commented 9 months ago

@yusukebe I modified it to specify runtime as an option for apapter and separate the process for each runtime. https://github.com/honojs/vite-plugins/compare/main...natsumesou:vite-plugins:fix-workerd-function

yusukebe commented 8 months ago

Hi @natsumesou !

I've released @hono/vite-dev-server@0.9.0 now. It provides a Cloudflare Adapter, so you can use it in your vite.config.ts. If you use it, the environment will be set as workerd.

import devServer from '@hono/vite-dev-server'
import cloudflareAdapter from '@hono/vite-dev-server/cloudflare'
import { defineConfig } from 'vite'

export default defineConfig({
  plugins: [
    devServer({
      entry: 'src/index.tsx',
      adapter: cloudflareAdapter
    })
  ]
})

Please try it.

natsumesou commented 8 months ago

@yusukebe I was unsure of the correct implementation and didn't think I could write tests, so this was extremely helpful. This PR ( #108 ) will be a great learning experience. Thank you very much!