发布于 2024-06-10, 更新于 2024-07-08
对博客进行了 Next.js 14 升级,整个过程非常平滑,很小的改动就可以获取全部新特性。迁移到新的 app 目录,并对应升级 SSG 模式,使得代码更简洁。
https://nextjs.org/docs/app/building-your-application/upgrading/version-14
升级依赖:
npm i next@latest react@latest react-dom@latest eslint-config-next@latest
npm i -D @types/react @types/react-dom
打包命令改动:
next build && next expor 中去掉 next export ,直接 next build 即可output: 'export',这样就可以了,跑起来以及打包都一切正常,不得不说这升级也太简单了。
app 目录是新版本增加的路由模式,是可选的。文档默认使用 app router ,旧版的 pages router 仍然支持,在文档左上角可切换使用的路由模式。
针对 pages 升级为 app 路由,文档也提供了迁移指南:
https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration
操作:
index.tsx 更名为 page.tsx, 直接用作路由的文件改为目录,内容写到 page.tsx 里_app.tsx 和 _document.tsx 改为 layout.tsx<Head> 标签修改useEffect 和 onClick 等组件改为客户端组件在 pages 中,使用 getStaticPaths 去生成同类所有页面,使用 getStaticProps 去生成单个页面的入参,这些在 app 目录发生了改变。
export const dynamic = 'error'; 来达到 pages 目录 getStaticProps 的效果,如未生成的路由跳到 404 页面。文档: https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config#dynamic