Appearance
hono-static
简介
hono-static 是 Hono 框架的静态文件服务中间件,它允许你轻松地提供静态资源文件,如 HTML、CSS、JavaScript、图片等。这个中间件支持缓存控制、条件请求和范围请求等特性,适合构建包含静态资源的 Web 应用。
安装
bash
npm install hono @hono/static-assets基本使用
typescript
import { Hono } from 'hono'
import { serveStatic } from '@hono/static-assets'
const app = new Hono()
// 提供单个文件
app.get('/favicon.ico', serveStatic({ path: './assets/favicon.ico' }))
// 提供目录中的所有文件
app.use('/static/*', serveStatic({ root: './public' }))
// 例如: /static/css/style.css 将提供 ./public/css/style.css
// 提供 SPA 应用的 index.html
app.get('*', serveStatic({ path: './dist/index.html' }))
app.listen(3000)高级配置
typescript
import { Hono } from 'hono'
import { serveStatic } from '@hono/static-assets'
import path from 'path'
const app = new Hono()
// 自定义配置
app.use(
'/assets/*',
serveStatic({
// 静态文件根目录
root: './public',
// 缓存控制
cache: {
// 浏览器缓存时间(秒)
maxAge: 60 * 60 * 24 * 30, // 30天
// 是否添加 ETag 头
etag: true,
// 是否添加 Last-Modified 头
lastModified: true,
// 是否处理条件请求 (If-None-Match, If-Modified-Since)
conditionalRequest: true,
},
// 自定义响应头
headers: {
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'DENY',
},
// 自定义 MIME 类型
mimeTypes: {
ts: 'application/typescript',
jsx: 'text/jsx',
mdx: 'text/mdx',
},
// 是否启用目录索引
index: true, // 当访问目录时自动查找 index.html
// 是否启用范围请求 (Range headers)
acceptRanges: true,
// 自定义 404 处理
notFound: (c) => {
return c.json({ error: '文件未找到' }, 404)
},
}),
)
// 不同路径使用不同配置
// 长期缓存的静态资源(通常包含哈希值的文件)
app.use(
'/static/assets/*',
serveStatic({
root: './dist/assets',
cache: {
maxAge: 60 * 60 * 24 * 365, // 1年
immutable: true, // 添加 immutable 标志
},
}),
)
// 短期缓存的静态资源
app.use(
'/static/images/*',
serveStatic({
root: './public/images',
cache: {
maxAge: 60 * 60 * 24, // 1天
},
}),
)注意事项
- 在生产环境中,考虑使用 CDN 或专门的静态文件服务器(如 Nginx)来提供静态资源
- 为包含哈希值的文件(如
main.a1b2c3.js)设置长期缓存,提高性能 - 确保静态文件目录不包含敏感信息,避免意外暴露
- 合理设置缓存时间,平衡性能和内容更新需求
- 对于大文件传输,确保启用范围请求支持,便于断点续传
- 在开发环境中,可以禁用缓存,确保始终获取最新文件