Bun

FileSystemRouter

Bun 提供了一個快速的 API,用於根據檔案系統路徑解析路由。此 API 主要供函式庫作者使用。目前僅支援 Next.js 風格的檔案系統路由,但未來可能會新增其他風格。

Next.js 風格

FileSystemRouter 類別可以根據 pages 目錄解析路由。(Next.js 13 的 app 目錄尚未支援。)請考慮以下 pages 目錄

pages
├── index.tsx
├── settings.tsx
├── blog
│   ├── [slug].tsx
│   └── index.tsx
└── [[...catchall]].tsx

FileSystemRouter 可用於根據此目錄解析路由

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 屬性中。

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 屬性中

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() 方法也接受 RequestResponse 物件。url 屬性將用於解析路由。

router.match(new Request("https://example.com/blog/my-cool-post"));

路由器會在初始化時讀取目錄內容。若要重新掃描檔案,請使用 .reload() 方法。

router.reload();

參考

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
  }
}