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

Contentlayer配置rehypePrettyCode时遭遇类型错误

问题

配置Contentlayer的rehypePrettyCode插件时触发类型错误:onVisitLine、onVisitHighlightedLine和onVisitHighlightedWord函数预期返回Transformer<any, any>或void类型,但当前返回的是Transformer<Root, Root>或void类型。

相关配置代码:

rehypePlugins: [
  rehypeSlug,
  [
    rehypePrettyCode,
    {
      theme: "poimandres",
      onVisitLine(node: RehypeNode) {
        // Prevent lines from collapsing in `display: grid` mode, and allow empty
        // lines to be copy/pasted
        if (node.children.length === 0) {
          node.children = [{ type: "text", value: " " }];
        }
      },
      onVisitHighlightedLine(node: RehypeNode) {
        node.properties.className.push("line--highlighted");
      },
      onVisitHighlightedWord(node: RehypeNode) {
        node.properties.className = ["word--highlighted"];
      },
    },
    rehypeAutolinkHeadings,
    {
      properties: {
        className: ["subheading-anchor"],
        ariaLabel: "Link to section",
      },
    },
  ],
],

package.json依赖:

{
  "dependencies": {
    "contentlayer": "^0.3.4",
    "rehype-pretty-code": "^0.12.0",
    "rehype-slug": "^6.0.0",
    "rehype-autolink-headings": "^7.1.0",
  }
}

解决方案

1. 修正插件配置结构

错误地将rehype-autolink-headings嵌套在rehype-pretty-code的配置数组中,导致插件解析异常。需将其单独作为rehypePlugins的一项:

rehypePlugins: [
  rehypeSlug,
  [
    rehypePrettyCode,
    {
      theme: "poimandres",
      onVisitLine(node: RehypeNode) {
        if (node.children.length === 0) {
          node.children = [{ type: "text", value: " " }];
        }
      },
      onVisitHighlightedLine(node: RehypeNode) {
        node.properties.className.push("line--highlighted");
      },
      onVisitHighlightedWord(node: RehypeNode) {
        node.properties.className = ["word--highlighted"];
      },
    },
  ],
  [
    rehypeAutolinkHeadings,
    {
      properties: {
        className: ["subheading-anchor"],
        ariaLabel: "Link to section",
      },
    },
  ],
],

2. 修复类型不匹配问题

  • 类型断言快速解决:如果不想额外安装类型包,可直接对节点做类型断言避免报错:
    onVisitHighlightedLine(node: any) {
      (node.properties.className as string[]).push("line--highlighted");
    },
    onVisitHighlightedWord(node: any) {
      node.properties.className = ["word--highlighted"];
    },
    
  • 导入正确类型:安装@types/hast开发依赖:
    npm install @types/hast --save-dev
    
    然后在配置文件中导入并替换RehypeNode:
    import type { Element } from "hast";
    
    // 配置中使用Element类型
    onVisitLine(node: Element) {
      if (node.children.length === 0) {
        node.children = [{ type: "text", value: " " }];
      }
    },
    

3. 版本兼容检查

当前contentlayer@0.3.4与rehype-pretty-code@0.12.0版本兼容,若上述方案无效,可尝试更新Contentlayer到最新稳定版:

npm update contentlayer

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 20:34:59