如何在 Next.js React Framework 中构建自定义/动态路由

How to build custom / dynamic routing in Next.js React Framework

我想在框架内实现动态路由,以便根据 CMS 中的页面生成路由。我已经阅读了文档,https://github.com/zeit/next.js#custom-server-and-routing 看起来可以完成这项工作。

const express = require('express')
const next = require('next')

const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

app.prepare()
.then(() => {
  const server = express()

  server.get('/', (req, res) => {
    return app.render(req, res, '/index', req.query)
  })

  server.get('/b', (req, res) => {
    return app.render(req, res, '/test', req.query)
  })

  server.get('*', (req, res) => {
    return handle(req, res)
  })

  server.listen(3000, (err) => {
    if (err) throw err
    console.log('> Ready on http://localhost:3000')
  })
})

我的问题是,这段代码在项目中放在哪里?我已尝试创建 ./server/server.js,但随后需要在 package.json 中更新我的启动脚本,但这些将需要指向 dist 版本,如 ./dist/server/server.js?

"scripts": {
    "build": "next build",
    "release": "fly release",
    "pretestonly": "fly pretest",
    "testonly": "cross-env NODE_PATH=test/lib jest \.test.js",
    "posttestonly": "fly posttest",
    "pretest": "npm run lint",
    "test": "npm run testonly -- --coverage --forceExit --runInBand --verbose --bail",
    "coveralls": "nyc --instrument=false --source-map=false report --temp-directory=./coverage --reporter=text-lcov | coveralls",
    "lint": "standard 'bin/*' 'client/**/*.js' 'examples/**/*.js' 'lib/**/*.js' 'pages/**/*.js' 'server/**/*.js' 'test/**/*.js'",
    "prepublish": "npm run release",
    "precommit": "lint-staged",
    "dev": "node ./dist/server/server.js",
    "start": "NODE_ENV=production node ./dist/server/server.js"
  },

./dist/server/server.js 路径不存在,即使在 运行 yarn run build

之后

Next.js 不会转换自定义服务器代码,因此您可以这样启动它:

"dev": "node ./server/server.js",
"start": "NODE_ENV=production node ./server/server.js"