Files
zhaoguiyang.site/mdx-integration-guide.md
joyzhao 398093dde9 feat(mdx): add MDX support and migrate markdown files to MDX
- Add @astrojs/mdx integration to enable MDX support
- Migrate all markdown files (.md) to MDX (.mdx) format
- Create HighlightBox component for enhanced content styling
- Update astro config to include MDX integration
- Add documentation guide for MDX integration
2025-06-20 11:36:11 +08:00

2.7 KiB
Raw Blame History

在Astro中使用Markdown组件的问题解决指南

问题分析

在Astro项目中您尝试在Markdown文件.md)中使用HighlightBox.astro组件但组件没有正确渲染。这是因为Astro的标准Markdown支持不允许直接在.md文件中使用Astro组件。

解决方案

要在Markdown文件中使用Astro组件HighlightBox.astro),您需要安装并配置@astrojs/mdx集成。MDX是Markdown的扩展允许在Markdown内容中使用JSX表达式和组件。

步骤1安装MDX集成

npm install @astrojs/mdx

步骤2配置Astro

astro.config.mjs文件中添加MDX集成

import { defineConfig } from 'astro/config';
import tailwindcss from "@tailwindcss/vite";
import react from "@astrojs/react";
import sitemap from "@astrojs/sitemap";
import mdx from '@astrojs/mdx'; // 添加这一行

// https://astro.build/config
export default defineConfig({
  site: 'https://zhaoguiyang.com',
  markdown: {
    shikiConfig: {
      theme: 'dracula',
    },
    remarkPlugins: [],
    rehypePlugins: [],
  },
  integrations: [
    react(), 
    sitemap({
      i18n: {
        defaultLocale: 'en',
        locales: {
          en: 'en',
          zh: 'zh'
        },
      },
    }),
    mdx(), // 添加这一行
  ],
  vite: {
      plugins: [tailwindcss()],
  },
  i18n: {
    defaultLocale: "en",
    locales: ["en", "zh"],
    routing: {
      prefixDefaultLocale: false,
    }
  },
});

步骤3将Markdown文件转换为MDX

将您的.md文件重命名为.mdx文件。例如:

  • about.mdabout.mdx
  • services.mdservices.mdx

步骤4确保正确导入组件

在MDX文件中确保正确导入组件

---
title: "About Me"
description: "Learn more about my background, skills, and experiences"
layout: "../layouts/AboutLayout.astro"
---

import HighlightBox from '../components/markdown/HighlightBox.astro';

# About Me

<HighlightBox type="info" title="Information">
  This is some important information.
</HighlightBox>

替代方案

如果您不想使用MDX还有以下替代方案

  1. 使用布局组件在Markdown文件中使用layout属性指定一个Astro布局组件然后在布局组件中添加您的HighlightBox组件。

  2. 使用remark或rehype插件您可以创建自定义的remark或rehype插件来转换Markdown中的特定语法为您的组件。

结论

Astro默认不支持在标准Markdown文件中直接使用组件这就是为什么您的HighlightBox组件没有正确渲染的原因。安装MDX集成是解决此问题的最直接方法它允许您在Markdown内容中使用完整的组件功能。