🧪 類型化路由
階段: 原型設計
提供在應用程式中建構 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
的檔案,用於訪問類型安全的路由網址、參數和搜尋參數
每個路由目錄
- 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>
);
});
- 使用標準連結並使用 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
,這將重新執行該過程並更新任何需要的變更