见我 杂函 思绪 造物 耕录

Astro 的 Mdx 和 Shiki 配置

2025 年 10 月 23 日

·

阅时约 2 分

tl;dr: Astro 的 Mdx 和 Shiki 配置

安装 shikiji-transformers:

bun i -D shikiji-transformers

添加配置:

import {
  transformerNotationDiff,
  transformerNotationErrorLevel,
  transformerNotationFocus,
  transformerNotationHighlight,
  transformerNotationWordHighlight
} from 'shikiji-transformers';

export default defineConfig({
  site: "https://www.xxsong.com",
  markdown: {
    syntaxHighlight: 'shiki',
    shikiConfig: {
      themes: {
        light: 'github-light',
        dark: 'github-dark'
      },
      transformers: [
        transformerNotationHighlight(),
        transformerNotationWordHighlight(),
        transformerNotationDiff(),
        transformerNotationErrorLevel(),
        transformerNotationFocus()
      ]
    }
  },
  integrations: [
    mdx(),
    sitemap({
      changefreq: "daily",
      priority: 1,
      lastmod: new Date().toISOString().split("T")[0],
    }),
    tailwind(),
    icon(),
  ],
  output: "server",
  adapter: cloudflare(),
});

由于 shiki 的 transformers 只在编译后的 html 中添加样式类,不会添加相应的 CSS,所以要自己添加样式:

/* shiki 代码主题 */
html.dark .astro-code {
  background-color: var(--shiki-dark-bg) !important;
}

html.dark .astro-code span {
  color: var(--shiki-dark) !important;
  /* Optional, if you also want font styles */
  font-style: var(--shiki-dark-font-style) !important;
  font-weight: var(--shiki-dark-font-weight) !important;
  text-decoration: var(--shiki-dark-text-decoration) !important;
}

/* 代码行 */
.astro-code .line {
  @apply relative inline-block w-full px-4;
}

/* 高亮行 */
.astro-code .highlighted {
  @apply pr-5 border-sky-400 bg-sky-300/15;
}
.astro-code .highlighted::before {
  content: '';
  @apply absolute left-0 inset-y-0 w-0.5 bg-blue-400;
}

/* 错误高亮 */
.astro-code .highlighted.error {
  @apply bg-red-400/15;
}
.astro-code .highlighted.error::before {
  @apply bg-red-400;
}

/* 警告高亮 */
.astro-code .highlighted.warning {
  @apply  bg-amber-400/15;
}
.astro-code .highlighted.warning::before {
  @apply bg-amber-400;
}

/* code diff */
.astro-code .diff.add,
.astro-code .diff.remove {
  @apply relative;
}
.astro-code .diff.add::before,
.astro-code .diff.remove::before {
  @apply absolute left-1;
}

/* 添加的行 */
.astro-code .diff.add {
  @apply bg-emerald-500/15;
}
.astro-code .diff.add::before {
  content: '+';
  @apply text-emerald-500;
}

/* 删除的行 */
.astro-code .diff.remove {
  @apply bg-red-500/15;
}
.astro-code .diff.remove::before {
  content: '-';
  @apply text-red-500;
}

/* 词高亮 */
.astro-code .highlighted-word {
  @apply box-border px-1 border border-solid border-gray-100/25 rounded-md;
}

然后在 md 或者 mdx 文档中写就可以看到效果了:

```ts
export function foo() {
  console.log('hewwo') 
  console.log('hello') 
}
```