Next.js13+Contentlayer语法高亮类型错误求助
解决Next.js+Contentlayer中rehype语法高亮工具的类型冲突错误
问题背景
基于Next.js 13、Tailwind与Contentlayer搭建博客时,使用rehype-pretty-code和rehype-highlight实现语法高亮,触发类型不兼容错误,具体报错如下:
Type '(options?: Readonly<Options> | null | undefined) => (tree: Root, file: VFile) => undefined' is not assignable to type 'Pluggable<any[]>'. Type '(options?: Readonly<Options> | null | undefined) => (tree: Root, file: VFile) => undefined' is not assignable to type 'Plugin<any[], any, any>'. Type '(tree: Root, file: VFile) => undefined' is not assignable to type 'void | Transformer<any, any>'. Type '(tree: Root, file: VFile) => undefined' is not assignable to type 'Transformer<any, any>'. Types of parameters 'file' and 'file' are incompatible. Type 'import("/Users/joonpark/Desktop/Projects/nextjs/joon-dev-blog/node_modules/vfile/lib/index").VFile' is not assignable to type 'import("/Users/joonpark/Desktop/Projects/nextjs/joon-dev-blog/node_modules/rehype-highlight/node_modules/vfile/lib/index").VFile'. Types of property 'messages' are incompatible. Type 'import("/Users/joonpark/Desktop/Projects/nextjs/joon-dev-blog/node_modules/vfile/node_modules/vfile-message/lib/index").VFileMessage[]' is not assignable to type 'import("/Users/joonpark/Desktop/Projects/nextjs/joon-dev-blog/node_modules/vfile-message/lib/index").VFileMessage[]'. Type 'VFileMessage' is missing the following properties from type 'VFileMessage': ancestors, place
当前使用的contentlayer.config.ts配置代码:
import { defineDocumentType, makeSource } from 'contentlayer/source-files'; import rehypeHighlight from 'rehype-highlight'; import rehypePrettyCode from 'rehype-pretty-code'; import remarkGfm from 'remark-gfm'; export const Post = defineDocumentType(() => ({ name: 'Post', filePathPattern: `**/*.mdx`, fields: { title: { type: 'string', required: true }, date: { type: 'date', required: true }, }, computedFields: { url: { type: 'string', resolve: (post) => `/posts/${post._raw.flattenedPath}`, }, }, })); /** @type {import('rehype-pretty-code').Options} */ const options = { theme: 'one-dark-pro', }; export default makeSource({ contentDirPath: 'posts', documentTypes: [Post], mdx: { remarkPlugins: [remarkGfm], rehypePlugins: [[rehypePrettyCode, options], rehypeHighlight], }, });
错误本质
这是依赖版本冲突导致的类型不兼容问题:项目中vfile和vfile-message包在不同依赖分支下存在多个版本(比如rehype-highlight依赖的旧版vfile与项目根依赖的新版vfile),二者的VFileMessage类型结构不一致,从而触发TypeScript类型检查报错。
解决方案
禁止手动修改
node_modules中的index.d.ts:这种修改是临时的,重新安装依赖后会被覆盖,无法持久解决问题。统一依赖版本:
- 在
package.json中添加版本强制统一配置:- npm用户使用
overrides字段:"overrides": { "vfile": "^5.3.7", "vfile-message": "^3.1.4" } - yarn用户使用
resolutions字段:"resolutions": { "vfile": "^5.3.7", "vfile-message": "^3.1.4" }
- npm用户使用
- 在
清理并重新安装依赖:
- 删除
node_modules目录以及package-lock.json(npm)或yarn.lock(yarn)文件 - 执行
npm install或yarn install重新安装依赖
- 删除
优化依赖使用:
rehype-pretty-code和rehype-highlight是功能重叠的语法高亮工具,只需保留其中一个即可,减少不必要的依赖冲突风险。
内容的提问来源于stack exchange,提问作者Joon Park
相关产品推荐
相关产品推荐

