radix3
基于基数树的轻量级快速 JavaScript 路由。
轻量、快速的 JavaScript 路由器,基于 基数树(Radix Tree)。
用法
安装包
# npm
npm i radix3
# yarn
yarn add radix3
# pnpm
pnpm i radix3
导入
// ESM
import { createRouter } from "radix3";
// CJS
const { createRouter } = require("radix3");
创建路由器实例并插入路由
const router = createRouter(/* options */);
router.insert("/path", { payload: "this path" });
router.insert("/path/:name", { payload: "named route" });
router.insert("/path/foo/**", { payload: "wildcard route" });
router.insert("/path/foo/**:name", { payload: "named wildcard route" });
匹配路由以访问匹配到的数据
router.lookup("/path");
// { payload: 'this path' }
router.lookup("/path/fooval");
// { payload: 'named route', params: { name: 'fooval' } }
router.lookup("/path/foo/bar/baz");
// { payload: 'wildcard route' }
router.lookup("/");
// null (no route matched for/)
方法
router.insert(path, data)
path
可以是静态的,也可以使用 :placeholder
或 **
来表示通配符路径。
匹配参数时将返回 data
对象。它应该是一个类似 { handler }
的对象,并且不包含保留关键字 params
。
router.lookup(path)
返回 path
对应的匹配数据,如果匹配的路由使用了占位符,则可选包含 params
键。
router.remove(path)
移除与 path
匹配的路由。
选项
你可以使用选项初始化路由器实例
const router = createRouter({
strictTrailingSlash: true,
routes: {
"/foo": {},
},
});
routes
: 一个对象,用于指定要添加的初始路由strictTrailingSlash
: 默认情况下,路由器在匹配和添加路由时会忽略末尾斜杠。当设置为true
时,带末尾斜杠的匹配会有所不同。
路由匹配器
从路由器树创建一个多重匹配器,它可以匹配路径对应的所有路由
import { createRouter, toRouteMatcher } from "radix3";
const router = createRouter({
routes: {
"/foo": { m: "foo" }, // Matches /foo only
"/foo/**": { m: "foo/**" }, // Matches /foo/<any>
"/foo/bar": { m: "foo/bar" }, // Matches /foo/bar only
"/foo/bar/baz": { m: "foo/bar/baz" }, // Matches /foo/bar/baz only
"/foo/*/baz": { m: "foo/*/baz" }, // Matches /foo/<any>/baz
},
});
const matcher = toRouteMatcher(router);
const matches = matcher.matchAll("/foo/bar/baz");
// [
// {
// "m": "foo/**",
// },
// {
// "m": "foo/*/baz",
// },
// {
// "m": "foo/bar/baz",
// },
// ]
路由匹配器导出
也可以从预编译规则导出并重新注入匹配器。
import { exportMatcher, createMatcherFromExport } from "radix3";
// Assuming you already have a matcher
// you can export this to a JSON-type object
const json = exportMatcher(matcher);
// and then rehydrate this later
const newMatcher = createMatcherFromExport(json);
const matches = newMatcher.matchAll("/foo/bar/baz");
性能
参见 基准测试。
许可
基于 charlieduong94/radix-router
的原创工作,由 Charlie Duong 制作 (MIT 许可)
MIT - 用 ❤️ 制作