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

Next.js 13 & Sanity v3中使用React Syntax Highlighter报错求助

解决Sanity v3 + Next.js 13中React Syntax Highlighter的Super expression错误

出现TypeError: Super expression must either be null or a function错误,核心原因是Next.js 13 App Router的服务器/客户端组件规则限制,以及React Syntax Highlighter的使用方式不匹配,以下是具体修复步骤:

1. 标记组件为客户端组件

Next.js 13 App Router默认所有组件为服务器组件,而React Syntax Highlighter依赖浏览器环境API,必须在客户端组件中运行。在代码文件顶部添加'use client'指令:

'use client'; // 必须添加这行

import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";
import { dark } from "react-syntax-highlighter/dist/esm/styles/prism";

2. 修正类型定义(弃用any)

使用Sanity官方提供的类型替代any,保证类型安全:

import type { PortableTextComponentProps } from '@portabletext/react';

// 替换原props: any的写法
code: (props: PortableTextComponentProps<{ code: string; language: string }>) => {
  return (
    <SyntaxHighlighter 
      language={props.value.language} 
      style={dark}
    >
      {props.value.code}
    </SyntaxHighlighter>
  );
},

3. 兼容导入路径(若仍报错)

如果ESM导入方式存在服务器端冲突,切换到CommonJS导入路径:

// 替换原导入语句
import { Prism as SyntaxHighlighter } from "react-syntax-highlighter/dist/cjs/react-syntax-highlighter-prism";
import { dark } from "react-syntax-highlighter/dist/cjs/styles/prism";

额外注意事项

  • 确保安装最新版依赖:npm install react-syntax-highlighter@latest
  • Sanity v3推荐使用@portabletext/react替代旧版@sanity/block-content-to-react
  • 禁止在服务器组件中直接渲染SyntaxHighlighter,必须通过客户端组件包裹

内容的提问来源于stack exchange,提问作者M Muqiit Faturrahman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 09:11:21