此 API 主要面向庫作者。目前僅支持 Next.js 風格的文件系統路由,但未來可能會添加其他風格。
Next.js 風格
FileSystemRouter 類可以根據 pages 目錄解析路由。(Next.js 13 的 app 目錄尚不支持。)考慮以下 pages 目錄:
txt
pages
├── index.tsx
├── settings.tsx
├── blog
│ ├── [slug].tsx
│ └── index.tsx
└── [[...catchall]].tsxFileSystemRouter 可用於根據此目錄解析路由:
ts
const router = new Bun.FileSystemRouter({
style: "nextjs",
dir: "./pages",
origin: "https://mydomain.com",
assetPrefix: "_next/static/"
});
router.match("/");
// =>
{
filePath: "/path/to/pages/index.tsx",
kind: "exact",
name: "/",
pathname: "/",
src: "https://mydomain.com/_next/static/pages/index.tsx"
}查詢參數將被解析並在 query 屬性中返回。
ts
router.match("/settings?foo=bar");
// =>
{
filePath: "/Users/colinmcd94/Documents/bun/fun/pages/settings.tsx",
kind: "dynamic",
name: "/settings",
pathname: "/settings?foo=bar",
src: "https://mydomain.com/_next/static/pages/settings.tsx",
query: {
foo: "bar"
}
}路由器將自動解析 URL 參數並在 params 屬性中返回它們:
ts
router.match("/blog/my-cool-post");
// =>
{
filePath: "/Users/colinmcd94/Documents/bun/fun/pages/blog/[slug].tsx",
kind: "dynamic",
name: "/blog/[slug]",
pathname: "/blog/my-cool-post",
src: "https://mydomain.com/_next/static/pages/blog/[slug].tsx",
params: {
slug: "my-cool-post"
}
}.match() 方法還接受 Request 和 Response 對象。url 屬性將用於解析路由。
ts
router.match(new Request("https://example.com/blog/my-cool-post"));路由器將在初始化時讀取目錄內容。要重新掃描文件,使用 .reload() 方法。
ts
router.reload();參考
ts
interface Bun {
class FileSystemRouter {
constructor(params: {
dir: string;
style: "nextjs";
origin?: string;
assetPrefix?: string;
fileExtensions?: string[];
});
reload(): void;
match(path: string | Request | Response): {
filePath: string;
kind: "exact" | "catch-all" | "optional-catch-all" | "dynamic";
name: string;
pathname: string;
src: string;
params?: Record<string, string>;
query?: Record<string, string>;
} | null
}
}