Next 中类型安全的声明式路由

不换
2024-04-24 01:37
阅读1.72分钟

引子

今天我们介绍一个工具 declarative-routing ,主要的目的是解决现有的 next 中的路由痛点:

<Link to={`/product/${product.id}`}>Product</Link>

如上所述,to 后面的链接如果发生变动需要随时维护,因为在 next 中的声明式路由取决于文件夹层级的嵌套命名规则。

经历过 declarative-routing 的转换后:

<ProductDetail.Link productId={product.id}>Product</ProductDetail.Link>

未来不论路由地址如何变化,所需要的参数如何增删,我们始终都是 映射组件传递属性。不得不讲,Jack Herrington 大佬的点子很新奇,对于程序扩展上是一个非常要好的思路。

介绍

下图是一个文件嵌套路由的转换依赖结果结构:

Preview

初始化

$ pnpx declarative-routing init

实时监听文件路由的改动,去动态声明路由结构,本质是启动了一个 node 的文件监听服务。

$ pnpx npx declarative-routing build:watch

改变使用方式

页面路由

从:

import Link from "next/link";
<Link href={`/product/${product.id}`}>Product</Link>;

到:

import { ProductDetail } from "@/routes";
<ProductDetail.Link productId={product.id}>Product</ProductDetail.Link>;
API

从:

// Data is any
const data = await fetch(`/api/product/${productId}`).then((res) => res.json());

到:

import { getProduct } from "@/routes";
// Data is strongly typed as the response of the getProduct function
const data = await getProduct({ productId });

本文做简要介绍,更多内容可以参考:Declarative-Routing Document

不换
不换
中国.上海