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
相关产品推荐
相关产品推荐

