MDX 组件演示

欢迎来到 MDX 组件演示页面!这里展示了 Astro + MDX 的核心能力,包括官方内置的 Shiki 代码高亮、多语言标签页、数学公式渲染、Mermaid 流程图和可折叠内容。

代码高亮(Shiki)

Astro 内置 Shiki 作为代码高亮引擎,支持 100+ 种语言和多套主题,零运行时开销。直接使用 Markdown 围栏代码块即可获得语法高亮。

Astro 组件

Example Titleastro
---
// src/components/Greeting.astro
interface Props {
  name: string;
  greeting?: string;
}

const { name, greeting = 'Hello' } = Astro.props;
---

<div class="greeting">
  <h1>{greeting}, {name}!</h1>
  <p>Welcome to my Astro site.</p>
</div>

<style>
  .greeting {
    font-family: sans-serif;
    padding: 1rem;
  }
</style>

Content Collections(类型安全内容)

typescript
// src/content/config.ts
import { defineCollection, z } from 'astro:content'

const blog = defineCollection({
  type: 'content',
  schema: z.object({
    title: z.string(),
    date: z.coerce.date(),
    tags: z.array(z.string()).default([]),
    draft: z.boolean().default(false),
    excerpt: z.string().optional(),
  }),
})

export const collections = { blog }

动态路由与静态生成

astro
---
// src/pages/blog/[slug].astro
import { getCollection } from 'astro:content';
import type { GetStaticPaths } from 'astro';

export const getStaticPaths: GetStaticPaths = async () => {
  const posts = await getCollection('blog', ({ data }) => !data.draft);
  return posts.map((post) => ({
    params: { slug: post.slug },
    props: { post },
  }));
};

const { post } = Astro.props;
const { Content } = await post.render();
---

<article>
  <h1>{post.data.title}</h1>
  <Content />
</article>

Astro Actions(服务端动作,v4.15+)

typescript
// src/actions/index.ts
import { defineAction } from 'astro:actions'
import { z } from 'astro:schema'

export const server = {
  newsletter: defineAction({
    input: z.object({
      email: z.string().email(),
    }),
    handler: async ({ email }) => {
      // 调用邮件服务 API
      await subscribeToNewsletter(email)
      return { success: true }
    },
  }),
}

View Transitions API

astro
---
// src/layouts/Layout.astro
import { ViewTransitions } from 'astro:transitions';
---

<html lang="zh-CN">
  <head>
    <ViewTransitions />
  </head>
  <body>
    <slot />
  </body>
</html>
astro
<!-- 页面元素动画标注 -->
<h1 transition:name="page-title" transition:animate="slide">
  {title}
</h1>

<img
  src={hero}
  transition:name={`hero-${slug}`}
  transition:animate="morph"
/>

Middleware(中间件)

typescript
// src/middleware.ts
import { defineMiddleware } from 'astro:middleware'

export const onRequest = defineMiddleware(async (context, next) => {
  const { pathname } = context.url

  // 权限检查
  if (pathname.startsWith('/admin')) {
    const session = context.cookies.get('session')
    if (!session) {
      return context.redirect('/login')
    }
  }

  // 注入本地化数据
  context.locals.lang = context.preferredLocale ?? 'zh-CN'

  return next()
})

多语言标签页

CodeTabs 组件提供 PostHog 风格的标签式代码切换,适合展示同一功能在不同包管理器或语言下的实现。

包管理器安装示例

npm install astro @astrojs/mdx @astrojs/tailwind

跨框架状态共享(Nanostores)

import { useStore } from '@nanostores/react'
import { cartItems, addItem } from '../stores/cart'

export function CartWidget() {
const items = useStore(cartItems)
return (
  <div>
    {items.map(item => (
      <div key={item.id}>{item.name} × {item.qty}</div>
    ))}
  </div>
)
}

数学公式

∫abf(x) dx\int_{a}^{b} f(x) \,dx

::: code-group

sh
npm install -D shiki
sh
yarn add -D shiki
sh
pnpm add -D shiki
sh
bun add -D shiki
sh
deno add npm:shiki

:::

行内数学表达式

这是爱因斯坦著名的质能方程,其中

表示能量,

表示质量,

表示光速。

复杂数学公式

交互式流程图

简单流程图

diagram

复杂系统架构图

时序图

diagram

可折叠内容

总结

这个演示页面展示了 Astro + MDX 的核心能力:

  1. Shiki 代码高亮 - 零运行时,支持 100+ 语言,双主题(亮/暗模式)
  2. CodeTabs 多语言标签页 - PostHog 风格,一键切换不同实现
  3. 数学公式渲染 - 支持 LaTeX 语法,完美显示数学表达式
  4. 交互式图表 - 支持流程图、时序图等多种 Mermaid 图表类型
  5. 可折叠内容 - PostHog 风格,提供更好的阅读体验

最后更新时间: 2024年1月22日