我强烈建议您尝试官方的 Next.js 示例:
Next.js -- 命名路由示例(next-routes)
https://github.com/zeit/next.js/tree/canary/examples/with-next-routes
但我发现它需要额外的服务器,如果我们将应用程序结构自定义为我自己的项目示例,它也会失败:
| src/app
| -- pages
| -- post.js
| -- category.js
| -- server.js (for routes)
| src/functions
| -- index.js (lambda function for server-side)
如果我运行next src/app,它将失败并出现以下错误:
Error: > Couldn't find a `pages` directory. Please create one under the project root
at findPagesDir (/home/paneladm/projects/paneladm-dev/travel-website/node_modules/next/dist/lib/find-pages-dir.js:3:170)
at new DevServer (/home/paneladm/projects/paneladm-dev/travel-website/node_modules/next/dist/server/next-dev-server.js:1:3491)
at createServer (/home/paneladm/projects/paneladm-dev/travel-website/node_modules/next/dist/server/next.js:2:105)
at Object.<anonymous> (/home/paneladm/projects/paneladm-dev/travel-website/src/app/server.js:14:13)
at Module._compile (module.js:653:30)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
at Function.Module.runMain (module.js:694:10)
Next.js 团队现在正在研究一个简单的解决方案
这添加了一个示例,展示了如何通过利用 Next.js 内置的新自定义路由支持来消除使用 next-routes 的现有应用程序对自定义服务器的需求
您应该将next 更新为9.1.+ 并实现您自己的路由,如下所示:
const nextRoutes = require('next-routes');
const routes = (module.exports = nextRoutes());
routes.add('category', '/category/:slug');
routes.add('post', '/post/:lang/:slug');
在您的next.config.js 文件中,启用experimental 属性并实现rewrites 方法如下:
const { routes } = require('./routes');
...
experimental: {
rewrites() {
const rewrites = [];
for (const route of routes) {
if (route.pattern !== route.page) {
rewrites.push({
source: route.pattern,
destination: route.page,
});
}
}
return rewrites;
}
},
现在你的结构应该是:
| src/app
| -- pages
| -- post.js
| -- category.js
但是,如果您想自定义页面,请尝试像这样更改路线:
...
routes.add('category/[slug]', '/category/:slug');
routes.add('post/[slug]', '/post/:lang/:slug');
它将指向pages --> category --> [slug].js 文件。
在新的PR implementation 文件中查看更多详细信息。
参考