今天我们介绍一个工具 declarative-routing ,主要的目的是解决现有的 next 中的路由痛点:
<Link to={`/product/${product.id}`}>Product</Link>
如上所述,to 后面的链接如果发生变动需要随时维护,因为在 next 中的声明式路由取决于文件夹层级的嵌套命名规则。
经历过 declarative-routing 的转换后:
<ProductDetail.Link productId={product.id}>Product</ProductDetail.Link>
未来不论路由地址如何变化,所需要的参数如何增删,我们始终都是 映射组件,传递属性。不得不讲,Jack Herrington 大佬的点子很新奇,对于程序扩展上是一个非常要好的思路。
下图是一个文件嵌套路由的转换依赖结果结构:

$ 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>;
从:
// 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