我想在框架内实现动态路由,以便根据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
路径也不存在
答案 0 :(得分:1)
Next.js不会转换自定义服务器代码,因此您可以这样启动它:
"dev": "node ./server/server.js",
"start": "NODE_ENV=production node ./server/server.js"