@btst/yar

中文文档
1.3.2发布于 2026/08/23MITTypeScriptESM + CJS构建来源已验证近 30 天下载 4537

Pluggable router for modern react frameworks

原始使用文档
文档目录10 节
  1. Why use this?
  2. Installation
  3. Quick Start
  4. Declarative Routes (less boilerplate)
  5. What You Need to Know
  6. createRoute(path, handler, options?, routeMeta?)
  7. createRouter(routes)
  8. Key Features
  9. Contributing
  10. License

@btst/yar (Yet Another Router)

A simple, type-safe router for React that works with any framework.

Why use this?

  • ✨ Super Simple - A tiny API: createRoute and createRouter (plus optional defineRoute/defineRoutes sugar)
  • 🔒 Type Safe - TypeScript knows your route params automatically
  • 🎯 Flexible - Works with any React framework
  • ✅ Validated - Built-in query parameter validation

Installation

npm install @btst/yar
# or
pnpm add @btst/yar

Quick Start

Here's one complete example showing all features:

import { createRoute, createRouter } from "@btst/yar";
import { z } from "zod"; // or any Standard Schema library
import HomePage from "./pages/home";
import BlogPostPage from "./pages/blog-post";

// 1️⃣ Simple route - just a page
const homeRoute = createRoute(
  "/",
  () => ({
    PageComponent: HomePage,
    meta: () => [{ name: "title", content: "Home" }],
  }),
  undefined,
  { isStatic: true } // 🏷️ Optional: tag routes for filtering for SSG environments
);

// 2️⃣ Dynamic route - with params, validation, and data loading
const blogRoute = createRoute(
  "/blog/:slug", // :slug becomes available as params.slug
  ({ params, query }) => ({
    PageComponent: BlogPostPage,
    
    // 📦 Load data (can use AbortSignal, options, etc.)
    loader: async (signal?: AbortSignal) => {
      const res = await fetch(`/api/posts/${params.slug}`, { signal });
      return res.json();
    },
    
    // 📄 Generate meta tags (can use loader data)
    meta: (post) => [
      { name: "title", content: post.title },
      { name: "description", content: post.excerpt },
    ],
    
    // 🎨 Extra data for anything (breadcrumbs, layout, etc.)
    extra: () => ({
      breadcrumbs: ["Home", "Blog", params.slug],
      layout: "blog",
    }),
  }),
  {
    // ✅ Validate query parameters
    query: z.object({
      preview: z.boolean().optional(),
    }),
  },
  { isStatic: false, requiresAuth: false } // 🏷️ Route tags
);

// 3️⃣ Create router
const router = createRouter({
  home: homeRoute,
  blog: blogRoute,
});

// 4️⃣ Use the router in your app
async function handleRequest(url: string) {
  const route = router.getRoute(url);
  
  if (!route) {
    return <NotFoundPage />;
  }

  // Everything is typed! TypeScript knows the types of all params
  const data = route.loader ? await route.loader() : null;
  const metaTags = route.meta ? route.meta(data) : [];
  const extras = route.extra ? route.extra() : null;

  return (
    <route.PageComponent 
      params={route.params} 
      data={data} 
    />
  );
}

// 5️⃣ Filter routes without running handlers (great for SSG!)
const staticRoutes = Object.values(router.routes)
  .filter(route => route.meta?.isStatic);

Declarative Routes (less boilerplate)

If you don't need custom closures per route, defineRoute and defineRoutes remove the handler wiring entirely. Components receive the route context (params, query) as props, and loader/meta/extra receive it as their first argument:

import { defineRoute, defineRoutes, createRouter } from "@btst/yar";

// Single route
const postRoute = defineRoute("/blog/:slug", {
  page: BlogPostPage, // rendered with { params, query } as props
  loading: Spinner,
  error: ErrorPage,
  loader: (ctx, signal?: AbortSignal) =>
    fetch(`/api/posts/${ctx.params.slug}`, { signal }).then((r) => r.json()),
  meta: (ctx, post) => [{ name: "title", content: post?.title ?? ctx.params.slug }],
  extra: (ctx) => ({ breadcrumbs: ["Home", "Blog", ctx.params.slug] }),
});

// Many routes at once, with optional page overrides
const routes = defineRoutes(
  {
    home: defineRoute("/", { page: HomePage }, undefined, { isStatic: true }),
    post: defineRoute("/blog/:slug", {
      page: BlogPostPage,
      loader: (ctx) => fetchPost(ctx.params.slug),
      meta: (ctx) => [{ name: "title", content: ctx.params.slug }],
    }),
  },
  { pages: { post: CustomPostPage } } // swap a page component per key
);

const router = createRouter(routes);

Overridden pages still receive the route context (params, query) as props. defineRoutes also accepts plain createRoute routes; overriding those swaps the PageComponent as-is.

defineRoute returns a regular route, so it composes freely with createRoute routes in the same createRouter call. Use createRoute when you need full control over the handler closure; use defineRoute/defineRoutes for the common declarative case.

What You Need to Know

createRoute(path, handler, options?, routeMeta?)

Creates a route. The handler returns:

  • PageComponent - Your React component
  • loader() - Load data (can accept any params like AbortSignal)
  • meta() - Generate SEO tags (can accept any params)
  • extra() - Any extra data you need (can accept any params)

The 4th parameter routeMeta lets you tag routes for filtering (e.g., { isStatic: true }).

createRouter(routes)

Combines your routes. Returns:

  • routes - All your routes
  • getRoute(path, query?) - Match a URL and get the route

Key Features

🎯 Path Parameters

"/blog/:slug" → params.slug is automatically typed

✅ Query Validation

query: z.object({ sort: z.string() })

🏷️ Route Tags

{ isStatic: true, requiresAuth: false }
// Filter without running handlers - perfect for finding static routes in SSG environments, or for filtering routes that require authentication.

🎨 Flexible Functions

loader: (signal) => fetch(url, { signal })
meta: (data) => [{ name: "title", content: data.title }]
extra: (userId) => ({ breadcrumbs: [...], userId })

Perfect for prefetching data and generating meta tags in SSR environments, or for adding extra data to your routes.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

MIT

版本与发布记录

@btst/yar 共发布 5 个版本,首次发布于 2025/10/14;过去 12 个月发布了 3 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
1.3.2latest2026/08/232 个月前
1.3.02026/07/044 个月前
1.2.02026/02/258 个月前
1.1.12025/10/161.1 年前
1.1.02025/10/141.1 年前

关于 @btst/yar 的常见问题

@btst/yar 是什么?

Pluggable router for modern react frameworks

如何安装 @btst/yar?

在项目目录运行 npm install @btst/yar,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@types/react(^18.0.0 || ^19.0.0)、@types/react-dom(^18.0.0 || ^19.0.0)、react(^18.0.0 || ^19.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@btst/yar 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@btst/yar 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@btst/yar 可以商用吗?

@btst/yar 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@btst/yar 的下载量有多少?

根据 npm 官方下载统计,@btst/yar 在 2026/10/09 – 2026/11/07 这 30 天内被下载 4,537 次,日均约 151 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@btst/yar 还在维护吗?

最新版本 1.3.2 发布于 2026/08/23(2 个月前);至今共发布 5 个版本,其中过去 12 个月发布了 3 个;首次发布于 2025/10/14。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。