Skip to content

Questa API è principalmente destinata agli autori di librerie. Al momento è supportato solo il routing file-system in stile Next.js, ma altri stili potrebbero essere aggiunti in futuro.

Stile Next.js ​

La classe FileSystemRouter può risolvere route contro una directory pages. (La directory app di Next.js 13 non è ancora supportata.) Considera la seguente directory pages:

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

Il FileSystemRouter può essere usato per risolvere route contro questa directory:

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

I parametri di query verranno parsati e restituiti nella proprietà 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"
  }
}

Il router parserà automaticamente i parametri URL e li restituirà nella proprietà 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"
  }
}

Il metodo .match() accetta anche oggetti Request e Response. La proprietà url verrà usata per risolvere la route.

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

Il router leggerà i contenuti della directory all'inizializzazione. Per rieseguire la scansione dei file, usa il metodo .reload().

ts
router.reload();

Riferimento ​

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 a cura di www.bunjs.com.cn