honojs / vite-plugins

Vite Plugins for Hono
https://hono.dev
103 stars 28 forks source link

Support reading env from `wrangler.toml` in dev server #133

Closed jamiehaywood closed 1 day ago

jamiehaywood commented 1 month ago

Currently I have a rudimentary function called getWranglerEnv that reads the env from the wrangler.toml and adds it to the env of the honox dev server. This is a proposal to add this as a plugin.

import pagesBuild from '@hono/vite-cloudflare-pages'
import pagesPlugin from '@hono/vite-dev-server/cloudflare-pages'
import { Env } from 'hono/types'
import honox from 'honox/vite'
import clientBuild from 'honox/vite/client'
import { defineConfig } from 'vite'

export default defineConfig(async ({ mode }) => {
  if (mode === 'client') {
    return {
      plugins: [clientBuild()]
    }
  } else {
    return {
      ssr: {
        external: ['react', 'react-dom', 'prop-types', 'react-is', 'hoist-non-react-statics', '@babel/runtime']
      },
      plugins: [
        honox({
          islands: true,
          devServer: {
            env: await getWranglerEnv(),
            plugins: [
              pagesPlugin({
                d1Databases: ['DB'],
                d1Persist: true
              })
            ]
          }
        }),
        pagesBuild()
      ]
    }
  }
})
async function getWranglerEnv(): Promise<Env> {
  const fs = await import('fs/promises')
  const toml = await import('toml')

  const wranglerToml = await fs.readFile('wrangler.toml', 'utf-8')
  const config = toml.parse(wranglerToml)

  console.log("Environment variables loaded from wrangler.toml")
  return config.vars[0]
}
yusukebe commented 1 month ago

Hi @jamiehaywood

Have you tried to use the adapter?

https://github.com/honojs/vite-plugins/tree/main/packages/dev-server#adapter-1

It will load bindings and environment variables from wrangler.toml.

yusukebe commented 1 day ago

I think we can do it with the adapter feature. Closing this.