You need to enable JavaScript to run this app. Next.js+TypeScript博客:[slug]动态路由构建报slug参数类型错误
优惠活动
大模型
产品
解决方案
定价
更多

Next.js+TypeScript博客:[slug]动态路由构建报slug参数类型错误

构建与运行报错修复方案

核心报错原因

  • 构建阶段触发的报错为:

    Build error occurred Error: A required parameter (slug) was not provided as a string in getStaticPaths for /blog/[slug]
    该报错确实和slug的运行时数据类型不匹配直接相关:这不是TypeScript编译层面的类型声明问题,是Next.js运行时的校验逻辑要求getStaticPaths返回的每一个路径参数,必须是明确的字符串类型值。当前代码直接取Contentful返回的item.fields.slug没有做空值过滤和类型收敛,一旦Contentful返回的内容里存在没有设置slug的条目,map出来的params里的slug就会是undefined/非字符串类型,直接触发构建校验失败。

  • 开发服务启动时触发的报错为:

    TypeError: Cannot read property 'tap' of undefined
    该报错和slug业务逻辑无关,属于Next.js依赖链的版本兼容问题,一般是本地依赖缓存损坏、Next.js和配套的webpack工具版本不匹配导致的连带报错。

代码调整步骤

按照以下要求修改[slug].tsx文件,即可解决构建阶段的slug校验问题:

  • 替换CommonJS的模块引入语法为ES标准模块引入,增加环境变量存在性校验,避免Contentful客户端初始化异常
  • 在getStaticPaths返回路径前,过滤掉没有配置有效slug的无效内容条目,显式将slug值转换为字符串类型,确保所有返回的路径参数符合Next.js的格式要求
  • 给getStaticProps的入参加空值判断,避免params为undefined时触发空指针报错
  • 给页面组件的入参增加明确的TypeScript类型定义,消除隐式any的类型检查报错

调整后的完整代码如下:

import type { GetStaticPaths, GetStaticProps } from 'next'
import { createClient } from 'contentful'

// 校验必要环境变量配置
if (!process.env.CONTENTFUL_SPACE_ID || !process.env.CONTENTFUL_ACCESS_TOKEN) {
  throw new Error('缺少Contentful对接的必要环境变量')
}

const client = createClient({
  space: process.env.CONTENTFUL_SPACE_ID,
  accessToken: process.env.CONTENTFUL_ACCESS_TOKEN,
})

// 定义文章数据结构类型
type Article = {
  fields: {
    title: string
    content: string
    slug: string
  }
}

type ArticlePageProps = {
  article: Article
}

export const getStaticPaths: GetStaticPaths = async () => {
  const data = await client.getEntries({
    content_type: 'article',
  })

  // 过滤无有效slug的条目,确保参数为字符串类型
  const validPaths = data.items
    .filter(item => typeof item.fields.slug === 'string' && item.fields.slug.trim())
    .map(item => ({
      params: {
        slug: String(item.fields.slug)
      }
    }))

  return {
    paths: validPaths,
    fallback: true,
  }
}

export const getStaticProps: GetStaticProps<ArticlePageProps> = async (context) => {
  const slug = context.params?.slug
  // 非法slug直接返回404
  if (typeof slug !== 'string') {
    return { notFound: true }
  }

  const data = await client.getEntries({
    content_type: 'article',
    'fields.slug': slug,
  })

  const article = data.items[0] as unknown as Article
  // 未匹配到对应文章直接返回404
  if (!article) {
    return { notFound: true }
  }

  return {
    props: {
      article
    }
  }
}

export default function ArticlePage({ article }: ArticlePageProps) {
  return (
    <article>
      <h1>{article.fields.title}</h1>
      <div>{article.fields.content}</div>
    </article>
  )
}

开发服务报错处理

完成上述代码调整后,按照以下步骤解决本地开发服务的启动报错:

  • 删除本地node_modules目录和yarn.lock缓存文件
  • 重新执行yarn install安装依赖,确保Next.js及其配套的webpack相关工具版本和官方匹配,不要手动安装版本不兼容的webpack依赖
  • 重启本地开发服务即可正常运行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.23 11:15:03