Next.js 15中generateStaticParams返回空数组致构建报错问题
Next.js 静态导出时
generateStaticParams 存在却报错的问题 我按配置使用 output: export 生成静态HTML文件,但执行 npm run build 时触发报错:
Error: Page "/products/[id]" is missing "generateStaticParams()" so it cannot be used with "output: export" config.
页面代码实现如下:
type Params = Promise<{ id: string }> const ProductPage = async (props: { params: Params }) => { const productId = (await props.params).id return ( <div> // content </div> ) } export default ProductPage export async function generateStaticParams() { return [] }
当前 package.json 配置:
{ "name": "test", "version": "0.1.0", "private": true, "scripts": { "dev": "next dev -p 3003", "build": "next build", "start": "next start", "lint": "next lint" }, "dependencies": { "@emotion/react": "^11.13.3", "@emotion/styled": "^11.13.0", "@material-design-icons/font": "^0.14.13", "@material-design-icons/svg": "^0.14.13", "@mui/icons-material": "^5.16.7", "@mui/material": "^5.16.7", "@mui/x-data-grid": "^7.15.0", "@tailwindcss/typography": "^0.5.15", "axios": "^1.7.6", "crypto-js": "^4.2.0", "js-cookie": "^3.0.5", "material-icons": "^1.13.12", "material-symbols": "^0.22.1", "next": "^15.0.3", "react": "^18", "react-dom": "^18", "react-markdown": "^9.0.1", "react-toastify": "^10.0.6", "remark-gfm": "^4.0.0", "sass": "^1.77.8", "swagger-ui-react": "^5.17.14" }, "devDependencies": { "@types/crypto-js": "^4.2.2", "@types/js-cookie": "^3.0.6", "@types/node": "^20", "@types/react": "^18", "@types/react-dom": "^18", "@types/swagger-ui-react": "^4.18.3", "postcss": "^8", "tailwindcss": "^3.4.1", "typescript": "^5" } }
问题原因及修复方案
报错核心有两个原因:
- 类型定义错误:
params在Next.js页面组件中是直接解析完成的对象,不需要用Promise包裹。 generateStaticParams返回值不符合Next.js 15的校验逻辑:空数组会被判定为无有效静态路径,需配合配置声明动态生成逻辑。
具体修复步骤:
修正类型定义
把Params类型改为普通对象,页面组件无需await直接读取参数:type Params = { id: string } const ProductPage = async (props: { params: Params }) => { const productId = props.params.id return ( <div> // content </div> ) }调整
generateStaticParams与页面配置
根据需求二选一:- 预渲染指定产品页面:返回需要预渲染的id数组
export async function generateStaticParams() { // 替换为实际获取产品ID的逻辑(如API请求) return [{ id: "1" }, { id: "2" }]; } - 运行时动态生成所有路径:添加
dynamicParams: true声明,同时保留空数组返回export const dynamicParams = true; export async function generateStaticParams() { return []; }
- 预渲染指定产品页面:返回需要预渲染的id数组
确认
next.config.js配置
确保已开启静态导出:/** @type {import('next').NextConfig} */ const nextConfig = { output: 'export', }; module.exports = nextConfig;
内容的提问来源于stack exchange,提问作者WillDFz
相关产品推荐
相关产品推荐

