← 全部文章

Astro 與 MDX——進階內容創作

什麼是 MDX?

MDX 讓你可以在 Markdown 文件中直接使用 JSX 組件。對於 Astro 來說,這意味著你的部落格文章不僅能包含文字和圖片,還能嵌入真正的互動組件。

# 我的文章

這裡是一段 Markdown 文字。

<Chart data={myData} />

在 Astro 中啟用 MDX

安裝官方整合:

pnpm add @astrojs/mdx

astro.config.mjs 中引入:

import mdx from '@astrojs/mdx';

export default defineConfig({
  integrations: [mdx()],
});

之後所有 .mdx 檔案就會自動被 Astro 識別。

MDX 的威力

嵌入 UI 組件

在 MDX 文章中直接使用你的 Astro 或 React 組件:

import Counter from '../../components/Counter.astro';
import Chart from '../../components/Chart.jsx';

## 互動示範

這個計數器是 Astro 組件:

<Counter initialValue={10} />

這個圖表是 React 組件:

<Chart data={salesData} />

使用 components 物件映射

你也可以在 frontmatter 中指定組件映射,讓 Markdown 元素被自訂組件取代:

---
title: '自訂 Markdown'
components:
  h1: FancyTitle
  img: ZoomableImage
---

# 這個標題會使用 FancyTitle 組件渲染

![這張圖片可以點擊放大](photo.jpg)

程式碼高亮

Astro 使用 Shiki 作為程式碼高亮引擎。你可以在配置中自訂主題:

export default defineConfig({
  markdown: {
    shikiConfig: {
      themes: { light: 'github-light', dark: 'github-dark' },
      defaultColor: false, // 支援雙主題
    },
  },
});

然後在 CSS 中控制:

html { --shiki-color-bg: #fff; }
html.dark { --shiki-color-bg: #0d1117; }

使用 Remark 和 Rehype 插件

MDX 支援強大的 Markdown 處理管線:

import remarkToc from 'remark-toc';
import rehypeAutolinkHeadings from 'rehype-autolink-headings';

export default defineConfig({
  markdown: {
    remarkPlugins: [remarkToc],
    rehypePlugins: [rehypeAutolinkHeadings],
  },
});

常用插件:

插件 用途
remark-toc 自動生成目錄
remark-gfm GFM(表格、任務列表)
rehype-autolink-headings 標題自動連結
rehype-pretty-code 進階程式碼格式化

MDX 與 Content Collections

在 Content Collection 中使用 MDX 非常簡單——確保你在 collection 的 loader 中包含 .mdx 檔案即可:

const posts = defineCollection({
  loader: glob({ pattern: "**/*.{md,mdx}", base: "./src/content/posts" }),
  // ...
});

然後在 MDX 文章中匯入組件時,這些組件會被視為文章的一部分,只在該文章需要時才載入其 JavaScript。

最佳實踐

  1. 保持 MDX 組件輕量:MDX 中的組件應以展示為主,避免複雜的副作用
  2. 共用組件放在 src/components/:建立一個一致的組件庫供 MDX 使用
  3. 逐一匯入:不要在 MDX 中批量 import *,以免載入過多不必要的程式碼
  4. 使用 frontmatter 管理 metadata:保持內容與配置分離

結語

MDX 是 Astro 內容創作中最強大的武器之一。它讓你可以把 Markdown 的書寫體驗和 Astro 組件的互動能力結合起來,寫出既有深度又有互動性的文章。對於技術部落格、教程和文件站點來說,這幾乎是完美的解決方案。