# 07aj-next-routes-extended 中文文档

规范地址：https://npmcn.com/package/07aj-next-routes-extended/

版本：0\.0\.1
npm 元数据更新时间：2022-04-04T10:08:10.169Z
中文译文更新时间：2026-10-31T11:41:18.824Z
软件包许可：MIT

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

原始 npm 页面：https://www.npmjs.com/package/07aj-next-routes-extended
原文对照：https://npmcn.com/package/07aj-next-routes-extended/?lang=original
项目主页：https://github.com/07abhishekrock/next-routes-extended#readme
源码仓库：https://github.com/07abhishekrock/next-routes-extended

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

- 包体积（解压后）：21.8 kB，8 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- 运行依赖：2 个
- peer 依赖：next \>=11，react \>=17
- 首次发布：2022-03-09T07:30:27.795Z
- 最新版本发布：2022-03-09T07:30:46.632Z
- 已发布版本数：2（近 12 个月 0 个）

## 中文简介

很容易在Next.js中使用通用动态路由

## 安装

```sh
npm install 07aj-next-routes-extended
```

也可以使用：`pnpm add 07aj-next-routes-extended`、`yarn add 07aj-next-routes-extended`、`bun add 07aj-next-routes-extended`

## README

# 动态路由为Next.js

[![npm version](https://d25lcipzij17d.cloudfront.net/badge.svg?id=js&type=6&v=1.5.2&x2=0)](https://www.npmjs.com/package/next-routes-extended) [![Coverage Status](https://coveralls.io/repos/github/meabed/next-routes-extended/badge.svg)](https://coveralls.io/github/meabed/next-routes-extended) [![Build Status](https://travis-ci.org/meabed/next-routes-extended.svg?branch=master)](https://travis-ci.org/meabed/next-routes-extended)

#### 这是从原始repo的版本派生出来的，并进行了一些增强

-   更新到最新的包（next.js和path-to-regexp）
-   更好的typescript支持
-   更多示例和实时代码沙箱
-   积极维护

#### 欢迎pr ！

易于使用通用动态路由 [Next.js](https://github.com/zeit/next.js)

-   快速风格的路由和参数匹配
-   express & co的请求处理程序中间件
-   `Link` 和 `Router` 通过路由定义生成url

## 示例

[CodeSandbox例子](https://codesandbox.io/s/nextjs-next-routes-7g4yu?file=/pages/index.tsx)

## 如何使用

安装:

```bash
npm install next-routes-extended --save
```

创建 `routes.js` 在您的项目中：

```javascript
const routes = require('next-routes-extended')

                                                    // Name   Page      Pattern
module.exports = routes()                           // ----   ----      -----
.add('about')                                       // about  about     /about
.add('blog', '/blog/:slug')                         // blog   blog      /blog/:slug
.add('user', '/user/:id', 'profile')                // user   profile   /user/:id
.add('/:noname/:lang(en|es)/:wow+', 'complex')      // (none) complex   /:noname/:lang(en|es)/:wow+
.add({name: 'beta', pattern: '/v3', page: 'v3'})    // beta   v3        /v3
```

该文件在服务器和客户机上都要使用。

API:

-   `routes.add([name], pattern = /name, page = name)`
-   `routes.add(object)`

参数:

-   `name` -路由名称
-   `pattern` -路线模式(如快车，见 [正则表达式路径](https://github.com/pillarjs/path-to-regexp)）
-   `page` -内页 `./pages` 待渲染

页面组件接收匹配的URL参数合并到 `query`

```javascript
export default class Blog extends React.Component {
  static async getInitialProps ({query}) {
    // query.slug
  }
  render () {
    // this.props.url.query.slug
  }
}
```

## 在服务器上

```javascript
// server.js
const next = require('next')
const routes = require('./routes')
const app = next({dev: process.env.NODE_ENV !== 'production'})
const handler = routes.getRequestHandler(app)

// With express
const express = require('express')
app.prepare().then(() => {
  express().use(handler).listen(3000)
})

// Without express
const {createServer} = require('http')
app.prepare().then(() => {
  createServer(handler).listen(3000)
})
```

你也可以选择传递一个自定义处理程序，例如：

```javascript
const handler = routes.getRequestHandler(app, ({req, res, route, query}) => {
  app.render(req, res, route.page, query)
})
```

一定要使用 `server.js` 在你的 `package.json` 脚本:

```json
"scripts": {
  "dev": "node server.js",
  "build": "next build",
  "start": "NODE_ENV=production node server.js"
}
```

## 在客户端

进口 `Link` 和 `Router` 从你的 `routes.js` 根据路由定义生成url：

### `Link` 例子

```jsx
// pages/index.js
import {Link} from '../routes'

export default () => (
  <div>
    <div>Welcome to Next.js!</div>
    <Link route='blog' params={{slug: 'hello-world'}}>
      <a>Hello world</a>
    </Link>
    or
    <Link route='/blog/hello-world'>
      <a>Hello world</a>
    </Link>
  </div>
)
```

API:

-   `<Link route='name'>...</Link>`
-   `<Link route='name' params={params}> ... </Link>`
-   `<Link route='/path/to/match'> ... </Link>`

道具:

-   `route` -路由名称或URL匹配(别名： `to`）
-   `params` -命名路由可选参数

生成的url `href` 和 `as` ,并呈现 `next/link`。其他道具 `prefetch` 也会起作用。

### `Router` 例子

```jsx
// pages/blog.js
import React from 'react'
import {Router} from '../routes'

export default class Blog extends React.Component {
  handleClick () {
    // With route name and params
    Router.pushRoute('blog', {slug: 'hello-world'})
    // With route URL
    Router.pushRoute('/blog/hello-world')
  }
  render () {
    return (
      <div>
        <div>{this.props.url.query.slug}</div>
        <button onClick={this.handleClick}>Home</button>
      </div>
    )
  }
}
```

API:

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

参数:

-   `route` —要匹配的路由名称或URL
-   `params` -命名路由可选参数
-   `options` -传递给Next.js

这同样适用于 `.replaceRoute()` 和 `.prefetchRoute()`

它生成url和调用 `next/router`

* * *

您还可以选择提供自定义 `Link` 和 `Router` 对象，例如：

```javascript
const routes = module.exports = require('next-routes-extended')({
  Link: require('./my/link')
  Router: require('./my/router')
})
```

* * *

##### 相关链接

-   [时间/ next.js](https://github.com/zeit/next.js) -用于服务器渲染React应用程序的框架
-   [正则表达式路径](https://github.com/pillarjs/path-to-regexp) -表达式样式的路径到regexp

## 常见问题

### 07aj-next-routes-extended 是什么？

很容易在Next\.js中使用通用动态路由

### 如何安装 07aj-next-routes-extended？

在项目目录运行 npm install 07aj-next-routes-extended，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：next（\>=11）、react（\>=17）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### 07aj-next-routes-extended 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### 07aj-next-routes-extended 支持 ESM 还是 CommonJS？

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

### 07aj-next-routes-extended 可以商用吗？

07aj-next-routes-extended 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### 07aj-next-routes-extended 还在维护吗？

最新版本 0\.0\.1 发布于 2022/03/09（4 年前）；至今共发布 2 个版本，其中过去 12 个月发布了 0 个；首次发布于 2022/03/09。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

