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

Astro:添加remark-code-extra插件后Shiki语法高亮失效

解决Astro中remark-code-extra与Shiki语法高亮冲突的问题

问题原因

remark-code-extra插件默认会将markdown中的代码块节点包裹在容器元素内,而Astro的Shiki语法高亮逻辑仅处理顶级代码块节点,导致被包裹的代码块无法被识别,从而失效。

解决方案

方案一:改用rehype-code-titles插件(推荐)

rehype插件在HTML转换阶段处理,不会干扰Shiki对代码块的识别,配置更简单:

  1. 安装插件
npm install rehype-code-titles --save-dev
  1. 修改astro.config.mjs配置
import tokyoStorm from "./src/code-themes/tokyo-storm.json";
import rehypeCodeTitles from "rehype-code-titles";

export default defineConfig({
  // 其他配置...
  markdown: {
    shikiConfig: {
      theme: tokyoStorm,
      wrap: true,
    },    
    rehypePlugins: [
      rehypeCodeTitles
    ]
  },
});
  1. 添加样式(与你原来的code-label样式一致)
.code-title {
  /* 替换为你原有的.code-label样式 */
}

使用时,在markdown代码块中通过title指定标签文本:

// 代码内容

方案二:调整remark-code-extra配置,禁用默认容器

如果坚持使用remark-code-extra,可通过配置禁用它的默认包裹容器,让代码块保持为顶级节点:

修改astro.config.mjs中的remarkPlugins配置,添加wrapper: null:

import tokyoStorm from "./src/code-themes/tokyo-storm.json";
import codeExtra from "remark-code-extra";

export default defineConfig({
  // 其他配置...
  markdown: {
    shikiConfig: {
      theme: tokyoStorm,
      wrap: true,
    },    
    remarkPlugins: [
      [codeExtra, {
        transform: node => node.meta ? ({
          before: [
            {
              type: 'element',
              tagName: 'div',
              properties: {
                class: "code-label"
              },
              children: [
                {
                  type: "element",
                  tagName: 'span',
                  children: [
                    {
                      type: "text",
                      value: node.meta
                    }
                  ]
                }
              ]
            }
          ],
          wrapper: null // 禁用默认包裹容器
        }) : null
      }]
    ]
  },
});

这样插件只会在代码块前添加标签元素,不会包裹代码块,Shiki就能正常识别并高亮了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 00:47:42