# @fuelrats/next-named-routes 中文文档

规范地址：https://npmcn.com/package/%40fuelrats/next-named-routes/

版本：3\.1\.1
npm 元数据更新时间：2022-04-05T12:53:06.342Z
中文译文更新时间：2026-11-15T16:11:05.832Z
软件包许可：BSD-3-Clause

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40fuelrats/next-named-routes
原文对照：https://npmcn.com/package/%40fuelrats/next-named-routes/?lang=original
项目主页：https://github.com/FuelRats/next-named-routes
源码仓库：https://github.com/FuelRats/next-named-routes

弃用说明：Next\.JS 10 now has automatic href resolution\. There are currently no plans on updating this package since the experience of defining routes has been greatly improved by the Next\.js team\.

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：22.4 kB，7 个文件
- 模块格式：CommonJS
- TypeScript 类型：未声明
- 运行依赖：2 个
- peer 依赖：next ^9\.2，react ^16\.6\.0，react-dom ^16\.6\.0
- 首次发布：2019-11-15T18:58:02.518Z
- 最新版本发布：2020-07-15T00:59:19.557Z
- 近 30 天下载量：4165（2026-10-16 至 2026-11-14，npm 官方下载统计）
- 已发布版本数：21（近 12 个月 0 个）

## 中文简介

Next.js 动态路由的 API 命名路线

## 安装

```sh
npm install @fuelrats/next-named-routes
```

也可以使用：`pnpm add @fuelrats/next-named-routes`、`yarn add @fuelrats/next-named-routes`、`bun add @fuelrats/next-named-routes`

## README

# @ flairrats/ next-name- routes (英语)

Next.js 9+动态路由的命名路由定义.

-   方便使用API来简化您应用程序内的路由.
-   从参数自动生成 URLS.
-   严格校验,防止出错.

## 目录

-   [安装](https://npmcn.com/package/%40fuelrats/next-named-routes/#readme-installation)
-   [定义应用程序中的路径](https://npmcn.com/package/%40fuelrats/next-named-routes/#readme-defining-routes-in-your-application)
    -   [函数路径](https://npmcn.com/package/%40fuelrats/next-named-routes/#readme-function-routes)
-   [使用 `<Link />`](https://npmcn.com/package/%40fuelrats/next-named-routes/#readme-using-link-)
    -   [`route` 作为定义的路由名称](https://npmcn.com/package/%40fuelrats/next-named-routes/#readme-route-as-a-defined-route-name)
    -   [`route` 作为文件路径](https://npmcn.com/package/%40fuelrats/next-named-routes/#readme-route-as-a-file-path)
    -   [处理参数](https://npmcn.com/package/%40fuelrats/next-named-routes/#readme-handling-parameters)
-   [使用 `Router`](https://npmcn.com/package/%40fuelrats/next-named-routes/#readme-using-router)
-   [提供自定义 `Link` 财务报告和审定财务报表 `Router`](https://npmcn.com/package/%40fuelrats/next-named-routes/#readme-providing-a-custom-link-and-router)
-   [从 `next-routes`](https://npmcn.com/package/%40fuelrats/next-named-routes/#readme-migrating-from-next-routes)
    -   [与 `next-routes`](https://npmcn.com/package/%40fuelrats/next-named-routes/#readme-differences-from-next-routes)

## 安装

1.  通过 : `yarn add @fuelrats/next-named-routes` 或者说 `npm i @fuelrats/next-named-routes`
2.  结构 `pages` 目录 [Next.js 动态路线](https://nextjs.org/docs/routing/dynamic-routes)。 。 。 .
3.  创建一个 `routes.js` 类似此项目的文件 :

```javascript
import routes from '@fuelrats/next-named-routes'


// Destructure what you need
const { Link, Router, useRouter, withRouter } = routes()
  .add('about', '/about-us') // define your routes
  .add('profile', '/profile/[tab]')
  .add('cms', '/cms/[...cmsPath]')


// export what you need
export { Link, Router, useRouter, withRouter }
```

4.  使用 `<Link />` 财务报告和审定财务报表 `Router` 在您的申请中!

## 定义应用程序中的路径

在大型应用路线中,会变得漫长而复杂. 你可以用这个 `.add()` 函数可以将您的路由化为简单的名称.

路线定义是完全可选的。 你可以用一个普通的 `href` 值可以不发行引用您的页面 !

用于 `.add()`,将函数标记在您的尾端 `routes()` 电话 :

```javascript
const { /* ... */ } = routes()
  .add(name, href)
```

`.add()` 接受两个论点:

-   **`name`** - 你的路线名称。 这将用来指代给定路径 。 可以是字符串或符号.
-   **`href`** - 你内心的路 `pages` 目录。 页:1 `href` 用于 `next/link` 财务报告和审定财务报表 `next/router`并接受 [函数](https://npmcn.com/package/%40fuelrats/next-named-routes/#readme-function-routes)。 。 。 .

如果成功,它将返回当前实例: `routes()` 这样你就可以把路由定义连在一起.

见 [使用 `<Link />`](https://npmcn.com/package/%40fuelrats/next-named-routes/#readme-using-link-) 财务报告和审定财务报表 [使用 `Router`](https://npmcn.com/package/%40fuelrats/next-named-routes/#readme-using-router) 下面是使用已定义路线的更详细信息.

### 函数路径

`.add()` 也接受对您路径定义行为的最终控制回调 。 这有利于当您想要将对象处理成路径 satters 时, 或者如果您想要根据参数的值来控制路径导致的页面 .

回调通过一个单一参数:

-   **`params`** - 给定的对象 `<Link />` 或者说 `Router` 调用

,并返回具有下列属性的对象:

-   **`href`** - 你内心的路 `pages` 目录.
-   **`as`** - 浏览器 URL 栏中将显示的路径 .
-   **`query`** - 要转换成查询字符串的参数对象( 可选)

```javascript
const { /* ... */ } = routes()
.add('forum post', ({ publishDate, slug, ...query }) => {
  const year = publishDate.getUTCFullYear()
  const month = publishDate.getUTCMonth()
  const day = publishDate.getUTCDate()

  return {
    href: '/forum/[year]/[month]/[day]/[slug]',
    as: `/forum/${year}/${month}/${day}/${slug}`,
    query,
  }
})
```

另一个例子是:

```javascript
.add('forum list', ({ category, page, ...query }) => {
  let href = '/forum'
  let as = '/forum'

  if (category) {
    href += '/cat/[category]'
    href += `/cat/${category}`

    if (page) {
      href += '/[page]'
      as += `/${page}`
    }
  }


  return { href, as, query }
})
```

## 使用 `<Link />`

提供的情况 `<Link />` 组件是包起来的 `next/link` 用于引用定义的路由,并通过参数生成最终的 URL.

-   **`route`** - 定义的路由名称或路径 `pages` 目录.
-   **`params`** - 用来生成URL和查询字符串的参数.
-   所有其他的道具 [`next/link`](https://nextjs.org/docs/api-reference/next/link)不过 `href` 财务报告和审定财务报表 `as` 被覆盖 `route` 如果它的定义.

### `route` 作为定义的路由名称

```javascript
import { Link } from '../routes'

const Nav = () => (
  <div>
    {/*
      * Equivalent to:
      * <Link
      *   href="/forums" />
      */}
    <Link route="forum list">
      <a>forums</a>
    </Link>

    {/*
      * Equivalent to:
      * <Link
      *   href="/forums/[year]/[month]/[day]/[slug]"
      *   as="/forums/2015/06/01/out-of-fuel-explorer-rescue-service-the-fuel-rats" />
      */}
    <Link route="forum post" params={{ year: '2015', month: '06', day: '01', slug: 'out-of-fuel-explorer-rescue-service-the-fuel-rats' }}>
      <a>Forum post</a>
    </Link>

    {/*
      * Equivalent to:
      * <Link
      *   href="/cms/[...cmsPath]"
      *   as="/cms/legal/terms-of-service" />
      */}
    <Link route="cms" params{{ cmsPath: [ 'legal', 'terms-of-service' ] }}>
        <a>Terms of Service</a>
    </link>
  </div>
)
)
```

### `route` 作为文件路径

也可以指未定义的路由 `routes.js` 使用页面路径 `pages` 目录.

```javascript
    {/*
      * Equivalent to:
      * <Link
      *   href="/profile/[tab]"
      *   as="/profile/overview" />
      */}
    <Link route="/profile/[tab]" params={{ tab: 'overview' }}>
      <a>Your Profile</a>
    </Link>
```

### 处理参数

路由编译器对于您动态路由所使用的参数很聪明. 例如:

未使用的参数将作为查询字符串传递到您的页面.

```javascript
    {/*
      * Equivalent to:
      * <Link
      *   href="/profile/[tab]?welcome=true"
      *   as="/profile/overview?welcome=true" />
      */}
    <Link route="/profile/[tab]" params={{ tab: 'overview', welcome: true }}>
      <a>Your Profile</a>
    </Link>
```

缺少参数将造成错误 .

```javascript
    {/* ERROR! "tab" is required */}
    <Link route="/profile/[tab]" params={{ welcome: true }}>
      <a>Your Profile</a>
    </Link>
```

## 使用 `Router`

这个 `Router` 对象ia 已修改 `next/router` 另有三个功能.

-   **`.pushRoute()`** - 包起来 `.push()`
-   **`.replaceRoute()`** - 包起来 `.replace()`
-   **`.prefetchRoute()`** - 包起来 `.prefetch()`

三个都接受相同的参数 表现得像他们的 `next/router` 对口单位

```javascript
import Router from '../routes'

Router.pushRoute(route, params, options)
```

-   **`route`** - 定义的路由名称或路径 `pages` 目录.
-   **`params`** - 用来生成URL和查询字符串的参数.
-   **`options`** - 说吧 `next/router` 选项对象.

`route` 财务报告和审定财务报表 `params` 参数接受与相应值相同的值 `<Link />` 以上道具.

## 提供自定义 `Link` 财务报告和审定财务报表 `Router`

你可以自己提供 `Link` 财务报告和审定财务报表 `Router` 但是,如果您想要扩展功能,则有一个主要提示。 页:1 `Router` 对象 **必须** 是一个既提供主要路由器 API 对象又提供 `useRouter()` 钩.

过 `Link` 财务报告和审定财务报表 `Router` 到以下路线:

```javascript
const RouterObj = {
  default: CustomRouter
  useRouter: customRouterHook
}

const {Link, Router} = routes(CustomLink, RouterObj)
```

虽然不方便,但我们要求这两种东西都能够提供包裹 `useRouter()` 钩子和 `withRouter()` (原始内容存档于2017-10-21). HoC.

习惯 `Router` 实值 **没有** 需要通过习惯 `Link` 组件。 一个可以存在 没有另一个.

## 从 `next-routes`

来自 [`next-routes`](https://github.com/fridays/next-routes)欢迎! 虽然我们没有提供完全相同的API,但使用它应该感到熟悉.

这个图书馆是 **没有** 一个简单的即时替换 `next-routes`。需要做一些工作来将您的路由定义转换为动态路由字符串格式,而且大多数高级正则ex匹配无法实现,因为 `next.js` 没有使用 `path-to-regexp`。 。 。 .

1.  遵循上述设置,对您进行调整 `routes.js` 文档.
2.  删除 `next-routes` 从您的服务器路由器。 在大多数情况下,这只涉及清除 `next-routes` 处理器包装器,然后库自导入 .
    -   如果您只执行一个用于动态路由的自定义服务器, 您有可能完全删除它 !
3.  删除 `next-routes` 通过 `yarn remove next-routes` 或者说 `npm r -S next-routes`

### 与 `next-routes`

-   参数 `routes.add()` 与 `next-routes`。更多信息见 [配置 `routes()`](https://npmcn.com/package/%40fuelrats/next-named-routes/#readme-configuring-routes) 上节.
    -   `name` 现在需要.
    -   `pattern`,我们称之为 `href`,是一个 `Next.js` 动态路由路径而不是一个 `path-to-regexp` 模式.
    -   `page`,或页面文件的路径,已不再需要,因为文件系统将始终反映 `href` 数值.

* * *

带给你的 [燃料老鼠队!](https://fuelrats.com/) ⛽🐀

## 常见问题

### @fuelrats/next-named-routes 是什么？

Next\.js 动态路由的 API 命名路线注意：该包已被作者标记为弃用——Next\.JS 10 now has automatic href resolution\. There are currently no plans on updating this package since the experience of defining routes has been greatly improved by the Next\.js team\.

### 如何安装 @fuelrats/next-named-routes？

在项目目录运行 npm install @fuelrats/next-named-routes，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：next（^9\.2）、react（^16\.6\.0）、react-dom（^16\.6\.0）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @fuelrats/next-named-routes 支持 TypeScript 吗？

该包的 package\.json 没有声明类型入口。需要类型提示时，可以在 npm 上查找社区维护的 @types/fuelrats\_\_next-named-routes 是否存在。

### @fuelrats/next-named-routes 支持 ESM 还是 CommonJS？

以 CommonJS 形式发布，可以直接 require\(\)；在 ES Module 项目中也可以用 import 引入（Node\.js 会把 module\.exports 作为默认导出）。

### @fuelrats/next-named-routes 可以商用吗？

@fuelrats/next-named-routes 使用 BSD-3-Clause 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。另外不得用原作者名义为衍生产品背书。以上为概括，不构成法律意见，请以许可原文为准。

### @fuelrats/next-named-routes 的下载量有多少？

根据 npm 官方下载统计，@fuelrats/next-named-routes 在 2026/10/16 – 2026/11/14 这 30 天内被下载 4,165 次，日均约 139 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @fuelrats/next-named-routes 还在维护吗？

最新版本 3\.1\.1 发布于 2020/07/15（6 年前）；至今共发布 21 个版本，其中过去 12 个月发布了 0 个；首次发布于 2019/11/16。作者已将其标记为弃用，新项目建议寻找替代方案。

