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