Skip to content

Commit

Permalink
feat(dev-server): exclude files in public dir (#191)
Browse files Browse the repository at this point in the history
* feat(dev-server): exclude files in `public` dir

* add changeset
  • Loading branch information
yusukebe authored Nov 11, 2024
1 parent ae89388 commit 1a9b685
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/unlucky-spoons-poke.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@hono/vite-dev-server': minor
---

feat: exlude files in `public` dir
5 changes: 5 additions & 0 deletions packages/dev-server/e2e/e2e.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,3 +101,8 @@ test('Should set `cf` properties', async ({ page }) => {
expect(res?.ok()).toBe(true)
expect(await res?.json()).toEqual({ cf: true })
})

test('Should return files in the public directory', async ({ page }) => {
const res = await page.goto('/hono-logo.png')
expect(res?.status()).toBe(200)
})
Binary file added packages/dev-server/e2e/public/hono-logo.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
18 changes: 17 additions & 1 deletion packages/dev-server/src/dev-server.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { getRequestListener } from '@hono/node-server'
import { minimatch } from 'minimatch'
import type { Plugin as VitePlugin, ViteDevServer, Connect } from 'vite'
import fs from 'fs'
import type http from 'http'
import path from 'path'
import type { Env, Fetch, EnvFunc, Adapter, LoadModule } from './types.js'

export type DevServerOptions = {
Expand Down Expand Up @@ -61,18 +63,32 @@ export const defaultOptions: Required<Omit<DevServerOptions, 'env' | 'adapter' |
}

export function devServer(options?: DevServerOptions): VitePlugin {
let publicDirPath = ''
const entry = options?.entry ?? defaultOptions.entry
const plugin: VitePlugin = {
name: '@hono/vite-dev-server',
configResolved(config) {
publicDirPath = config.publicDir
},
configureServer: async (server) => {
async function createMiddleware(server: ViteDevServer): Promise<Connect.HandleFunction> {
return async function (
req: http.IncomingMessage,
res: http.ServerResponse,
next: Connect.NextFunction
): Promise<void> {
const exclude = options?.exclude ?? defaultOptions.exclude
if (req.url) {
const filePath = path.join(publicDirPath, req.url)
try {
if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
return next()
}
} catch {
// do nothing
}
}

const exclude = options?.exclude ?? defaultOptions.exclude
for (const pattern of exclude) {
if (req.url) {
if (pattern instanceof RegExp) {
Expand Down

0 comments on commit 1a9b685

Please sign in to comment.