You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NextJS中MyApp.getInitialProps返回pageProps为空,如何获取所有生成页面

你在自定义_app.jsx中声明了getInitialProps,而如果你的页面使用getStaticProps做静态生成(SSG),Next.js默认不会将页面getStaticProps返回的数据注入到_app的pageProps中,同时还会关闭所有页面的自动静态优化,这就是你打印pageProps为空的直接原因。

如果仅需要修复pageProps为空的问题,直接删除MyApp.getInitialProps这段逻辑即可,删除后页面getStaticProps返回的数据会自动传递到_app的pageProps参数中。

以下是获取所有已生成页面的可行方案,按使用场景区分:

方案1:构建阶段获取所有页面列表

适合需要在构建时就拿到全量页面信息、提前生成静态资源的场景,在next.config.js中配置exportPathMap即可拿到所有已生成页面的路径:

const fs = require('fs')
const path = require('path')

module.exports = {
  exportPathMap: async function (defaultPathMap) {
    // defaultPathMap的key就是所有页面的路由路径
    const allPagePaths = Object.keys(defaultPathMap)
    // 可以将路径列表写入本地json文件,后续项目代码中直接引入使用
    fs.writeFileSync(
      path.resolve(__dirname, './all-generated-pages.json'),
      JSON.stringify(allPagePaths, null, 2)
    )
    return defaultPathMap
  }
}

方案2:运行时服务端获取所有页面列表

适合服务端接口、SSR逻辑中需要动态获取当前已生成页面的场景,直接读取构建产物目录即可:

import fs from 'fs/promises'
import path from 'path'

async function getAllGeneratedPages() {
  // 静态生成的页面产物都存在该目录下
  const pagesDir = path.join(process.cwd(), '.next', 'server', 'pages')
  const fileList = await fs.readdir(pagesDir, { recursive: true })
  
  return fileList
    // 过滤掉系统内置页面和非页面文件
    .filter(file => {
      const fileName = path.basename(file)
      return file.endsWith('.html') && !['_app.html', '_document.html', '_error.html'].includes(fileName)
    })
    // 转换为标准路由路径格式
    .map(file => {
      const routePath = path.relative(pagesDir, file).replace(/\.html$/, '').replace(/\\/g, '/')
      return routePath === 'index' ? '/' : `/${routePath}`
    })
}

方案3:静态导出场景获取所有页面

如果你使用next export将站点导出为纯静态文件,直接读取导出的out目录下的html文件即可,逻辑和方案2一致,只需把读取目录改为path.join(process.cwd(), 'out')即可。

注意:1000个页面的量级下,以上方案的执行性能都不会有问题,无需额外优化。

内容的提问来源于stack exchange,提问作者jonask

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 04:15:08