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

Next.js中出现SyntaxError: Unexpected token 'export'错误求助

解决react-syntax-highlighter刷新页面出现Unexpected token 'export'错误

问题复现

渲染代码时出现以下错误,初次运行正常,刷新页面触发报错:

SyntaxError: Unexpected token 'export'
(项目路径)/node_modules/react-syntax-highlighter/dist/esm/styles/prism/index.js

代码示例:

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

const codeString = '(num) => num + 1';

const Code = () => {
  return (
    <div>
      <SyntaxHighlighter language="javascript" style={oneLight}>
        {codeString}
      </SyntaxHighlighter>
    </div>
  );
};

export default Code;

解决方案

1. 切换到CommonJS模块导入

将ES模块风格的样式导入替换为CommonJS版本,避免构建工具解析ES模块时的冲突:

// 替换前
import { oneLight } from "react-syntax-highlighter/dist/esm/styles/prism";
// 替换后
import { oneLight } from "react-syntax-highlighter/dist/cjs/styles/prism";

2. 配置构建工具处理依赖转译

如果需要保留ES模块导入,可让构建工具对react-syntax-highlighter进行转译:

  • Webpack项目:在webpack配置文件中添加:
module.exports = {
  // 其他配置项
  transpileDependencies: ['react-syntax-highlighter']
}
  • Vite项目:在vite.config.js中配置:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
  optimizeDeps: {
    include: ['react-syntax-highlighter']
  }
})

3. 检查并更新依赖版本

确保react-syntax-highlighter版本与你的React版本兼容,执行更新命令:

npm update react-syntax-highlighter
# 或使用yarn
yarn upgrade react-syntax-highlighter

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 09:09:19