name: Bun Next.js description: 这个技能应用于用户询问关于“Next.js与Bun”、“Bun和Next”、“在Bun上运行Next.js”、“使用Bun进行Next.js开发”、“使用Bun创建Next.js应用”或使用Bun作为运行时构建Next.js应用程序的情况。 version: 1.0.0
Bun Next.js
使用Bun运行Next.js应用程序,以实现更快的开发和构建。
快速开始
# 使用Bun创建新的Next.js项目
bunx create-next-app@latest my-app
cd my-app
# 安装依赖
bun install
# 开发
bun run dev
# 构建
bun run build
# 生产环境
bun run start
项目设置
package.json
{
"scripts": {
"dev": "next dev --turbo",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"next": "^16.1.1",
"react": "^19.2.3",
"react-dom": "^19.2.3"
}
}
使用Bun作为运行时
{
"scripts": {
"dev": "bun --bun next dev",
"build": "bun --bun next build",
"start": "bun --bun next start"
}
}
--bun标志强制Next.js使用Bun的运行时,而不是Node.js。
配置
next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
// 启用实验性功能
experimental: {
// Turbopack(更快开发)
turbo: {},
},
// 服务器端Bun API
serverExternalPackages: ["bun:sqlite"],
// Webpack配置(如果需要)
webpack: (config, { isServer }) => {
if (isServer) {
// 允许Bun特定导入
config.externals.push("bun:sqlite", "bun:ffi");
}
return config;
},
};
module.exports = nextConfig;
在Next.js中使用Bun API
服务器组件
// app/page.tsx(服务器组件)
import { Database } from "bun:sqlite";
export default async function Home() {
const db = new Database("data.sqlite");
const users = db.query("SELECT * FROM users").all();
db.close();
return (
<div>
{users.map((user) => (
<p key={user.id}>{user.name}</p>
))}
</div>
);
}
API路由
// app/api/users/route.ts
import { Database } from "bun:sqlite";
export async function GET() {
const db = new Database("data.sqlite");
const users = db.query("SELECT * FROM users").all();
db.close();
return Response.json(users);
}
export async function POST(request: Request) {
const body = await request.json();
const db = new Database("data.sqlite");
db.run("INSERT INTO users (name) VALUES (?)", [body.name]);
db.close();
return Response.json({ success: true });
}
文件操作
// app/api/files/route.ts
export async function GET() {
const file = Bun.file("./data/config.json");
const config = await file.json();
return Response.json(config);
}
export async function POST(request: Request) {
const data = await request.json();
await Bun.write("./data/config.json", JSON.stringify(data, null, 2));
return Response.json({ saved: true });
}
服务器动作
// app/actions.ts
"use server";
import { Database } from "bun:sqlite";
import { revalidatePath } from "next/cache";
export async function createUser(formData: FormData) {
const name = formData.get("name") as string;
const db = new Database("data.sqlite");
db.run("INSERT INTO users (name) VALUES (?)", [name]);
db.close();
revalidatePath("/users");
}
export async function deleteUser(id: number) {
const db = new Database("data.sqlite");
db.run("DELETE FROM users WHERE id = ?", [id]);
db.close();
revalidatePath("/users");
}
中间件
// middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
export function middleware(request: NextRequest) {
// 检查认证
const token = request.cookies.get("token");
if (!token && request.nextUrl.pathname.startsWith("/dashboard")) {
return NextResponse.redirect(new URL("/login", request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ["/dashboard/:path*"],
};
环境变量
# .env.local
DATABASE_URL=./data.sqlite
API_SECRET=your-secret-key
// 在服务器组件/动作中访问
const dbUrl = process.env.DATABASE_URL;
const secret = process.env.API_SECRET;
// 暴露给客户端(前缀使用NEXT_PUBLIC_)
// .env.local
NEXT_PUBLIC_API_URL=https://api.example.com
部署
为生产环境构建
bun run build
bun run start
Docker
FROM oven/bun:1
WORKDIR /app
COPY package.json bun.lockb ./
RUN bun install --frozen-lockfile
COPY . .
RUN bun run build
EXPOSE 3000
CMD ["bun", "run", "start"]
Vercel
# 安装Vercel CLI
bun add -g vercel
# 部署
vercel
注意:Vercel的边缘运行时使用V8,而不是Bun。Bun API在以下情况工作:
- 服务器组件(Node.js运行时)
- API路由(Node.js运行时)
- 服务器动作(Node.js运行时)
性能提示
-
使用Turbopack以加速开发:
bun run dev --turbo -
优先使用服务器组件 - 发送到客户端的JavaScript更少
-
使用Bun SQLite代替外部数据库用于简单应用
-
启用压缩:
// next.config.js module.exports = { compress: true, };
常见错误
| 错误 | 原因 | 修复方法 |
|---|---|---|
找不到bun:sqlite |
运行时错误 | 使用bun --bun next dev |
模块未找到 |
缺少依赖 | 运行bun install |
水合不匹配 |
服务器/客户端差异 | 检查数据获取 |
边缘运行时错误 |
在边缘使用Bun API | 使用Node.js运行时 |
何时加载参考
加载references/app-router.md当:
- App路由器模式
- 路由组
- 并行路由
加载references/caching.md当:
- 数据缓存策略
- 重新验证模式
- 静态生成