使用Next.js App Router在Vercel触发按需重验证时Shiki主题缺失报错
解决Vercel部署Next.js时shiki主题文件找不到的问题
问题原因
本地构建时node_modules完整存在,能正常读取shiki主题文件;但Vercel生产环境中,打包工具会对依赖做树摇优化,当用字符串'one-dark-pro'指定主题时,工具无法识别需要打包对应的JSON文件,导致运行时(尤其是按需重验证触发服务器端渲染时)出现文件找不到的报错。
解决方案
1. 手动导入主题文件
直接从shiki包中导入对应的主题JSON文件,让打包工具明确识别需要包含该资源:
import { serialize } from 'next-mdx-remote/serialize'; import readingTime from 'reading-time'; import remarkGfm from 'remark-gfm'; import rehypeSlug from 'rehype-slug'; import rehypeAutolinkHeadings from 'rehype-autolink-headings'; import rehypePrettyCode from 'rehype-pretty-code'; // 手动导入主题JSON文件 import oneDarkProTheme from 'shiki/themes/one-dark-pro.json'; /** @type {import('rehype-pretty-code').Options} */ const options = { // 使用导入的主题对象替换原字符串 theme: oneDarkProTheme, onVisitLine(node: any) { if (node.children.length === 0) { node.children = [{ type: 'text', value: ' ' }]; } }, onVisitHighlightedLine(node: any) { node.properties.className.push('line--highlighted'); }, onVisitHighlightedWord(node: any) { node.properties.className = ['word--highlighted']; }, }; export async function mdxToHtml(source: any) { const mdxSource = await serialize(source, { mdxOptions: { remarkPlugins: [remarkGfm], rehypePlugins: [ rehypeSlug, [rehypePrettyCode, options], [ rehypeAutolinkHeadings, { properties: { className: ['anchor'], }, }, ], ], format: 'mdx', }, }); return { html: mdxSource, wordCount: source.split(/\s+/gu).length, readingTime: readingTime(source).text, }; }
2. 验证依赖兼容性
确保shiki和rehype-pretty-code版本匹配,避免因版本差异导致主题文件路径或结构变化,可执行命令更新依赖:
npm install shiki@latest rehype-pretty-code@latest
3. 重新部署
修改代码后重新提交并部署到Vercel,测试按需重验证功能是否正常运行。
内容的提问来源于stack exchange,提问作者Pratham
相关产品推荐
相关产品推荐

