🧪 类型化路由
阶段: 原型设计
提供在应用程序中构建 URL 的类型安全方式。
安装
npm install github:QwikDev/qwik-labs-build#main
- 更新
vite.config.ts
// ... import { qwikTypes } from '@builder.io/qwik-labs/vite'; export default defineConfig(() => { return { plugins: [ // ... qwikTypes() // <== Add `qwikTypes()` to the list of plugins ], // ... }; });
- 运行构建,以便它生成
~/routes.gen.d.ts
和~/routes.config.tsx
文件。 - 要创建类型安全的链接
import { AppLink } from '~/routes.config'; export default component$(() => { // ... return ( // ... <AppLink route="/your/[appParam]/link/" param:appParam={"some-value"}> Link text </AppLink> ); });
声明式路由
这是一个最初由 Jack Herrington(又名“蓝领程序员”)为 NextJS 应用程序中的类型安全路由创建的包,并已改编为在 QwikCity 中使用。
安装
npx declarative-routing init
设置
初始化过程将为您创建一些重要的文件。
.src/declarativeRoutes
makeRoute.ts
- 用于定义页面路由index.ts
- 所有路由文件将从这里导入。hooks.ts
- 一个包含两个自定义钩子useParams
和useSearchParams
的文件,用于访问类型安全的路由 URL、参数和搜索参数
每个路由目录
- routeInfo.ts - 在这里命名路由,并为
params
和search
(搜索参数)提供zod
模式
用法
声明路由详细信息
/src/routes/pokemon/[pokemonId]/routeInfo.ts
import { z } from "zod";
export const Route = {
name: "PokemonDetail",
params: z.object({
pokemonId: z.coerce.number(),
}),
};
组件内部
您可以在组件中使用声明式路由的几种不同方式。
- 使用 RouteName.Link
myComponent.tsx
import { PokemonDetail } from "~/declarativeRoutes
export default component$(() => {
// ...
return (
// ...
<PokemonDetail.Link pokemonId={1}>Bulbasaur</PokemonDetail.Link>
);
});
- 使用标准 Link 并使用 RouteName 作为函数来返回路径
myComponent.tsx
import { Link } from "@builder.io/qwik-city";
import { PokemonDetail } from "~/declarativeRoutes
export default component$(() => {
// ...
return (
// ...
<Link href={PokemonDetail({ pokemonId: 1 })}>Bulbasaur</Link>
);
});
- 使用 RouteName.ParamsLink
myComponent.tsx
import { PokemonDetail } from "~/declarativeRoutes";
export default component$(() => {
// ...
return (
// ...
<PokemonDetail.ParamsLink params={{ pokemonId: 1 }}>Bulbasaur</PokemonDetail.ParamsLink>
);
});
- 从 RouteName 获取参数
myComponent.tsx
import { PokemonDetail } from "~/declarativeRoutes";
export default component$(() => {
// Typescript will know the correct params and their types
const { pokemonId } = useParams(PokemonDetail);
// ...
return (
// ...
);
});
添加或更改路由
如果您添加了新的路由或移动了现有路由,只需运行 npx declarative-routing build
,这将重新运行该过程并更新任何必要的更改。