07aj-next-routes-extended 中文文档教程

发布于 3年前 浏览 11 项目主页 更新于 3年前

Dynamic Routes for Next.js

npm version覆盖状态构建状态

This is forked from version of the original repo with some enhancements

  • Updates to the latest packages ( next.js and path-to-regexp )
  • Better typescript support
  • More examples and live codesandbox
  • Actively maintained

PRs are welcome!

易于使用通用动态路由

  • Express-style route and parameters matching
  • Request handler middleware for express & co
  • Link and Router that generate URLs by route definition

Examples

Next.js CodeSandbox 示例

How to use

安装:

npm install next-routes-extended --save

在您的项目中创建 routes.js

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 - Route name
  • pattern - Route pattern (like express, see path-to-regexp)
  • page - Page inside ./pages to be rendered

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

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

On the server

// 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)
})

您可以选择传递自定义处理程序,例如:

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

确保在 server.js 中使用 server.js code>package.json 脚本:

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

On the client

routes.js 文件中导入 LinkRouter 以根据路由定义生成 URL:

Link example

// 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 - Route name or URL to match (alias: to)
  • params - Optional parameters for named routes

它为 hrefas 生成 URL 并呈现 next/linkprefetch 等其他属性也可以使用。

Router example

// 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 - Route name or URL to match
  • params - Optional parameters for named routes
  • options - Passed to Next.js

同样适用于 .replaceRoute().prefetchRoute()

它生成 URL 并调用 next/router


您可以选择提供自定义 LinkRouter 对象,例如:

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

Dynamic Routes for Next.js

npm versionCoverage StatusBuild Status

This is forked from version of the original repo with some enhancements

  • Updates to the latest packages ( next.js and path-to-regexp )
  • Better typescript support
  • More examples and live codesandbox
  • Actively maintained

PRs are welcome!

Easy to use universal dynamic routes for Next.js

  • Express-style route and parameters matching
  • Request handler middleware for express & co
  • Link and Router that generate URLs by route definition

Examples

CodeSandbox Example

How to use

Install:

npm install next-routes-extended --save

Create routes.js inside your project:

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

This file is used both on the server and the client.

API:

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

Arguments:

  • name - Route name
  • pattern - Route pattern (like express, see path-to-regexp)
  • page - Page inside ./pages to be rendered

The page component receives the matched URL parameters merged into query

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

On the server

// 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)
})

Optionally you can pass a custom handler, for example:

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

Make sure to use server.js in your package.json scripts:

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

On the client

Import Link and Router from your routes.js file to generate URLs based on route definition:

Link example

// 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>

Props:

  • route - Route name or URL to match (alias: to)
  • params - Optional parameters for named routes

It generates the URLs for href and as and renders next/link. Other props like prefetch will work as well.

Router example

// 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)

Arguments:

  • route - Route name or URL to match
  • params - Optional parameters for named routes
  • options - Passed to Next.js

The same works with .replaceRoute() and .prefetchRoute()

It generates the URLs and calls next/router


Optionally you can provide custom Link and Router objects, for example:

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

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文