【Bun中文文档-API】FileSystemRouter

297 阅读1分钟

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

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