Skip to content

이 API 는 주로 라이브러리 작성자를 위한 것입니다. 현재는 Next.js 스타일의 파일 시스템 라우팅만 지원되지만 다른 스타일도 향후 추가될 수 있습니다.

Next.js 스타일

FileSystemRouter 클래스는 pages 디렉토리에 대해 라우트를 해결할 수 있습니다. (Next.js 13 의 app 디렉토리는 아직 지원되지 않습니다.) 다음 pages 디렉토리를 고려해 보세요:

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

FileSystemRouter 는 이 디렉토리에 대해 라우트를 해결하는 데 사용할 수 있습니다:

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() 메서드는 RequestResponse 객체도 받습니다. 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
  }
}

Bun by www.bunjs.com.cn 편집