如何通过外部包为Next.js应用添加页面且无需放入/pages目录?
Next.js 无需将页面放入/pages目录的实现方案
完全可以实现,根据你使用的Next.js路由模式不同,有以下几种常用方案:
Pages Router 适用方案
方案1:极简代理导出(最稳定)
你不需要把页面组件代码复制到/pages目录,只需要在/pages下新建一个和路由对应的空白文件,直接导出自定义包的页面组件及配套的data fetch方法即可,示例:
// /pages/custom-path.js export { default, getStaticProps, getServerSideProps } from '@your-custom-package/target-page'
如果你的自定义包需要转译,在next.config.js中加入以下配置即可:
// next.config.js module.exports = { // Next.js 13.1+ 支持 transpilePackages,无需安装额外插件 transpilePackages: ['@your-custom-package'] }
方案2:无需在/pages下新增文件的webpack entry注入
如果你连/pages下的代理文件都不想加,可以直接在next.config.js的webpack配置中,往Next.js的pages入口列表里注入你自定义包的页面:
// next.config.js module.exports = { webpack: (config) => { const originalEntry = config.entry // 注入自定义页面,路由为/custom-route,对应包内文件@your-custom-package/custom-page config.entry = async () => { const entries = await originalEntry() entries['pages/custom-route'] = require.resolve('@your-custom-package/custom-page') return entries } return config } }
App Router 适用方案
App Router模式下实现更简单,只需要在对应路由的page.js中直接导出自定义包的页面组件即可:
// /app/custom-route/page.js export { default } from '@your-custom-package/target-page'
如果需要服务端/客户端组件声明,直接在该文件顶部加'use client'或者'use server'指令即可。
注意事项
- 注入的页面组件完全兼容Next.js的所有原生能力,包括静态生成、服务端渲染、路由跳转等
- 如果自定义包依赖Next.js的内置模块,需要确保自定义包的peerDependencies中声明了对应版本的next、react、react-dom,避免版本冲突
内容的提问来源于stack exchange,提问作者Konstantin Komelin
相关产品推荐
相关产品推荐

