Skip to content

Fix Lỗi Svelte Components trong Starlight MDX

Khi sử dụng Astro Starlight kết hợp với Svelte, bạn sẽ gặp phải lỗi build nếu import Svelte components trực tiếp trong MDX files. Bài viết này sẽ hướng dẫn bạn cách khắc phục vấn đề này.

Lỗi 1: MDXError - Could not parse import/exports

Section titled “Lỗi 1: MDXError - Could not parse import/exports”
Terminal window
[@mdx-js/rollup] Could not parse import/exports with acorn: ...

Nguyên nhân: Starlight có MDX processor riêng không tương thích với Svelte imports trong frontmatter.

Terminal window
MDXError: Unexpected end of file

Nguyên nhân: Dấu ngoặc nhọn { trong tables không được escape đúng cách.

Giải pháp 1: Gỡ bỏ Svelte Integration

Section titled “Giải pháp 1: Gỡ bỏ Svelte Integration”

Nếu không cần thiết phải dùng Svelte trong MDX, hãy gỡ Svelte ra khỏi astro.config.mjs:

astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';
// import svelte from '@astrojs/svelte'; // ❌ Comment out hoặc xóa
export default defineConfig({
integrations: [
starlight({
title: 'My Docs',
// svelte(), // ❌ Không dùng nữa
}),
],
});

Giải pháp 2: Sử dụng starlight-markdown-blocks

Section titled “Giải pháp 2: Sử dụng starlight-markdown-blocks”

Đây là giải pháp được khuyến nghị để tạo custom blocks mà không cần Svelte:

Terminal window
npm install starlight-markdown-blocks

Cấu hình trong astro.config.mjs:

import starlightMarkdownBlocks from 'starlight-markdown-blocks';
export default defineConfig({
integrations: [
starlight({
title: 'My Docs',
plugins: [
starlightMarkdownBlocks({
blocks: {
terminal: {
render: ({ h, label, children }) =>
h('div', { class: 'terminal-block' }, [
h('div', { class: 'terminal-header' }, [
h('div', { class: 'terminal-buttons' }, [
h('span', { class: 'close' }),
h('span', { class: 'minimize' }),
h('span', { class: 'maximize' }),
]),
h('span', { class: 'terminal-title' }, label || 'Terminal'),
]),
h('div', { class: 'terminal-body' }, children),
]),
},
},
}),
],
}),
],
});

Giải pháp 3: Escape braces trong Tables

Section titled “Giải pháp 3: Escape braces trong Tables”

Khi sử dụng braces { trong tables, hãy escape chúng:

| Cú pháp | Mô tả |
|---------|-------|
| {variable} | Dấu ngoặc nhọn |
Tính năngSvelte Componentstarlight-markdown-blocks
Cài đặtCần Svelte integrationCần plugin riêng
PropsĐầy đủHạn chế
StylingTự doPhải custom render
Build timeChậm hơnNhanh hơn
  • Khuyến nghị: Sử dụng starlight-markdown-blocks cho các custom blocks đơn giản
  • Tránh: Import Svelte components trực tiếp trong MDX frontmatter
  • Lưu ý: Luôn escape {} thành {} trong tables