honojs / vite-plugins

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

feat(dev-server): introduce `env` #30

Closed yusukebe closed 1 year ago

yusukebe commented 1 year ago

This PR introduces the concept of ENV and the env option.

For Cloudflare Pages, the current cf option allows us to use bindings. For example:

export default defineConfig({
  plugins: [
    devServer({
      entry: 'src/index.ts',
      cf: {
        bindings: {
          NAME: 'Hono',
        },
      },
    }),
  ],
})

With this configuration, we can access variables through c.env:

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

This is currently exclusive to Cloudflare Pages, but in the future, it may be extended to other runtimes/platforms with specific environment values. While c.env seems to be used for Cloudflare, other platforms/runtimes may also use bindings/c.env. For instance, the AWS Lambda adapter currently uses env:

https://github.com/honojs/hono/blob/main/src/adapter/aws-lambda/handler.ts#L126-L143

This PR suggests separating the Cloudflare Pages-specific functionality from dev-server.ts. With this change, the getEnv() method for Cloudflare Pages is placed in cloudflare-pages/index.ts, and users can include the env in their vite.config.ts:

import { getEnv } from '@hono/vite-dev-server/cloudflare-pages'

// ...

export default defineConfig({
  plugins: [
    devServer({
      env: getEnv({
        bindings: {
          NAME: 'Hono',
        },
      }),
    }),
  ],
})

With this mechanism, adding support for another platform that uses environment variables becomes straightforward:

import { getEnv } from '@hono/vite-dev-server/another-one'

// ...

export default defineConfig({
  plugins: [
    devServer({
      env: getEnv({
        someFunction: {
          NAME: 'Hono',
        },
      }),
    }),
  ],
})
yusukebe commented 1 year ago

Hey @Code-Hex !

Could you review this?

changeset-bot[bot] commented 1 year ago

🦋 Changeset detected

Latest commit: 1e7f4ae27c3a323f5fd97d1b6947ae269cba1ac2

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package | Name | Type | | --------------------- | ----- | | @hono/vite-dev-server | Minor |

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

yusukebe commented 1 year ago

@Code-Hex

Thanks for reviewing. Let's go with this!