@basenative/router

中文文档
3.0.0发布于 2026/10/31Apache-2.0TypeScriptES Module构建来源已验证

SSR-aware path routing with named params, wildcards, and history API integration

原始使用文档
文档目录14 节
  1. Install
  2. Quick Start
  3. API
  4. createRouter(routes, options?)
  5. resolveRoute(routes, path)
  6. compilePattern(pattern)
  7. matchRoute(compiled, path)
  8. parseQuery(search) / buildQuery(params)
  9. interceptLinks(router, options?)
  10. Navigation Guards — @basenative/router/guards
  11. withGuards(router)
  12. redirect(to, replace = true)
  13. RedirectError
  14. License

@basenative/router

Signal-based client-side router with SSR-aware path matching

Part of the BaseNative ecosystem — a signal-based web runtime over native HTML.

Install

npm install @basenative/router

Quick Start

import { createRouter, interceptLinks } from '@basenative/router';

const router = createRouter([
  { path: '/', name: 'home' },
  { path: '/users/:id', name: 'user' },
  { path: '/blog/:slug*', name: 'blog' },
]);

// Read reactive current route
import { effect } from '@basenative/runtime';

effect(() => {
  const route = router.currentRoute();
  console.log(route.name, route.params, route.query);
});

// Navigate programmatically
router.navigate('/users/42');

// Intercept <a> clicks for client-side navigation
interceptLinks(router);

API

createRouter(routes, options?)

Creates a router instance. Returns an object with:

  • currentRoute — Computed signal with { name, path, params, query, matched }.
  • navigate(to, options?) — Pushes a new entry to history (replace: true to replace instead).
  • back() — Navigates back in browser history.
  • forward() — Navigates forward in browser history.

Options

  • base — Path prefix applied to all routes (e.g. '/app').

resolveRoute(routes, path)

Resolves a path against a route list without creating a router instance. Useful for SSR.

compilePattern(pattern)

Compiles a route pattern string into a matcher object. Supports :param, :param* (wildcard), and exact segments.

matchRoute(compiled, path)

Tests a compiled pattern against a path. Returns a params object on match, null on no match.

parseQuery(search) / buildQuery(params)

Parse a query string into an object, or serialize an object into a query string.

interceptLinks(router, options?)

Attaches a click listener to document that intercepts <a href> clicks and calls router.navigate() instead of triggering a full page load. Respects target, download, and external links.

Navigation Guards — @basenative/router/guards

Opt-in — createRouter() and the router it returns are unaffected unless you wrap it. Import from the /guards subpath (also re-exported from the package root):

import { createRouter } from '@basenative/router';
import { withGuards, redirect } from '@basenative/router/guards';

const router = withGuards(createRouter(routes));

router.beforeEach(({ to, from }) => {
  if (to.name === 'dashboard' && !isAuthenticated()) {
    return redirect('/login'); // or: return '/login'; or: return false;
  }
});

router.afterEach(({ to }) => {
  document.title = to.matched?.title ?? 'App';
});

const ok = await router.navigate('/dashboard'); // Promise<boolean>

withGuards(router)

Wraps a router instance (from createRouter()) and returns a GuardedRouter with the same pathname / query / currentRoute / back() / forward() / routes, plus:

  • navigate(to, options?) — same as the wrapped router's, but returns Promise<boolean>: true once navigation and all afterEach handlers have run, false if a guard aborted or redirected it.
  • beforeEach(guard) — registers a guard, run in registration order against a preview of the destination route before the URL changes. Returns a disposer that unregisters it.
  • afterEach(handler) — registers a handler invoked (with { to, from, options }) once navigation commits. Returns a disposer.

A guard receives { to, from, options } (to/from are ResolvedRoutes; from is null on the very first navigation) and may return:

  • undefined / nothing — let navigation proceed.
  • false — abort navigation with no redirect.
  • a path string, or { redirect, replace? } — abort and redirect to that path.
  • throw redirect(to, replace?) (or a RedirectError directly) — same as above, usable from deep inside a guard.
  • throw anything else — propagates and rejects the navigate() call; it is not treated as an abort.

Guards run sequentially; the first one that aborts stops the chain — later guards do not run. Starting a new navigate() call while a previous one's guards are still running aborts the in-flight call, which then resolves false.

redirect(to, replace = true)

Throws a RedirectError that withGuards()'s guard runner catches and turns into a redirect. Never returns.

RedirectError

The error class redirect() throws. Has to: string and replace: boolean properties; can also be thrown directly with throw new RedirectError(to, replace).

License

Apache-2.0

版本与发布记录

@basenative/router 共发布 11 个版本,首次发布于 2026/03/20;过去 12 个月发布了 11 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
3.0.0latest2026/10/312 天前
2.4.02026/10/268 天前
2.3.22026/10/2212 天前
2.3.12026/10/2212 天前
2.3.02026/10/2212 天前
2.2.02026/10/2113 天前

关于 @basenative/router 的常见问题

@basenative/router 是什么?

具有命名参数、通配符和历史记录API集成的SSR感知路径路由

如何安装 @basenative/router?

在项目目录运行 npm install @basenative/router,或使用 pnpm add / yarn add / bun add。

@basenative/router 支持 TypeScript 吗?

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

@basenative/router 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@basenative/router 可以商用吗?

@basenative/router 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@basenative/router 还在维护吗?

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