npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

hono-vite-dev-server-hmr

v0.1.1

Published

Vite dev-server plugin for Hono

Downloads

4

Readme

@hono/vite-dev-server

@hono/vite-dev-server is a Vite Plugin that provides a custom dev-server for fetch-based web applications like those using Hono. You can develop your application with Vite. It's fast.

Features

  • Support any fetch-based applications.
  • Hono applications run on.
  • Fast by Vite.
  • HMR (Only for the client side).
  • Plugins are available, e.g., Cloudflare Pages.
  • Also runs on Bun.

Demo

https://github.com/honojs/vite-plugins/assets/10682/a93ee4c5-2e1a-4b17-8bb2-64f955f2f0b0

Supported applications

You can run any application on @hono/vite-dev-server that uses fetch and is built with Web Standard APIs. The minimal application is the following.

export default {
  fetch(_request: Request) {
    return new Response('Hello Vite!')
  },
}

This code can also run on Cloudflare Workers or Bun. And if you change the entry point, you can run on Deno, Vercel, Lagon, and other platforms.

Hono is designed for fetch-based applications like this.

import { Hono } from 'hono'

const app = new Hono()

app.get('/', (c) => c.text('Hello Vite!'))

export default app

So, any Hono application will run on @hono/vite-dev-server.

Usage

Installation

You can install vite and @hono/vite-dev-server via npm.

npm i -D vite @hono/vite-dev-server

Or you can install them with Bun.

bun add vite @hono/vite-dev-server

Settings

Add "type": "module" to your package.json. Then, create vite.config.ts and edit it.

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

export default defineConfig({
  plugins: [
    devServer({
      entry: 'src/index.ts', // The file path of your application.
    }),
  ],
})

Development

Just run vite.

npm exec vite

Or

bunx --bun vite

Options

The options are below.

export type DevServerOptions = {
  entry?: string
  export?: string
  injectClientScript?: boolean
  exclude?: (string | RegExp)[]
  ignoreWatching?: (string | RegExp)[]
  adapter?: {
    env?: Env
    onServerClose?: () => Promise<void>
  }
}

Default values:

export const defaultOptions: Required<Omit<DevServerOptions, 'cf'>> = {
  entry: './src/index.ts',
  injectClientScript: true,
  exclude: [
    /.*\.css$/,
    /.*\.ts$/,
    /.*\.tsx$/,
    /^\/@.+$/,
    /\?t\=\d+$/,
    /^\/favicon\.ico$/,
    /^\/static\/.+/,
    /^\/node_modules\/.*/,
  ],
  ignoreWatching: [/\.wrangler/],
}

injectClientScript

If it's true and the response content type is "HTML", inject the script that enables Hot-reload. default is true.

exclude

The paths that are not served by the dev-server.

If you have static files in public/assets/* and want to return them, exclude /assets/* as follows:

import devServer, { defaultOptions } from '@hono/vite-dev-server'
import { defineConfig } from 'vite'

export default defineConfig({
  plugins: [
    devServer({
      exclude: ['/assets/.*', ...defaultOptions.exclude],
    }),
  ],
})

ignoreWatching

You can add target directories for the server to watch.

adapter

You can pass the env value of a specified environment to the application.

Adapter

Cloudflare

You can pass the Bindings specified in wrangler.toml to your application by using "Cloudflare Adapter".

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

export default defineConfig(async () => {
  return {
    plugins: [
      devServer({
        adapter: cloudflareAdapter,
      }),
    ],
  }
})

Client-side

You can write client-side scripts and import them into your application using Vite's features. If /src/client.ts is the entry point, simply write it in the script tag. Additionally, import.meta.env.PROD is useful for detecting whether it's running on a dev server or in the build phase.

app.get('/', (c) => {
  return c.html(
    <html>
      <head>
        {import.meta.env.PROD ? (
          <script type='module' src='/static/client.js'></script>
        ) : (
          <script type='module' src='/src/client.ts'></script>
        )}
      </head>
      <body>
        <h1>Hello</h1>
      </body>
    </html>
  )
})

In order to build the script properly, you can use the example config file vite.config.ts as shown below.

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

export default defineConfig(({ mode }) => {
  if (mode === 'client') {
    return {
      build: {
        rollupOptions: {
          input: ['./app/client.ts'],
          output: {
            entryFileNames: 'static/client.js',
            chunkFileNames: 'static/assets/[name]-[hash].js',
            assetFileNames: 'static/assets/[name].[ext]',
          },
        },
        emptyOutDir: false,
        copyPublicDir: false,
      },
    }
  } else {
    return {
      build: {
        minify: true,
        rollupOptions: {
          output: {
            entryFileNames: '_worker.js',
          },
        },
      },
      plugins: [
        devServer({
          entry: './app/server.ts',
        }),
      ],
    }
  }
})

You can run the following command to build the client script.

vite build --mode client

Frequently Asked Questions

exports is not defined

If you use a package that only supports CommonJS, you will encounter the error exports is not defined.

exports is not defined

In that case, specify the target package in ssr.external in vite.config.ts:

export default defineConfig({
  ssr: {
    external: ['react', 'react-dom'],
  },
  plugins: [devServer()],
})

Importing Asset as URL is not working

If you want to import assets as URL with the following code, the logo image may not be found.

import { Hono } from 'hono'

import logo from './logo.png'

const app = new Hono()

app.get('/', async (c) => {
  return c.html(
    <html>
      <body>
        <img src={logo} />
      </body>
    </html>
  )
})

export default app

This is because logo.png is served from this dev-server, even though it is expected to be served from Vite itself. So to fix it, you can add *.png to the exclude option:

import devServer, { defaultOptions } from '@hono/vite-dev-server'

export default defineConfig({
  plugins: [
    devServer({
      entry: 'src/index.tsx',
      exclude: [/.*\.png$/, ...defaultOptions.exclude],
    }),
  ],
})

Authors

License

MIT