Fix Lỗi Svelte Components trong Starlight MDX
Tổng quan
Section titled “Tổng quan”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 phổ biến
Section titled “Lỗi phổ biến”Lỗi 1: MDXError - Could not parse import/exports
Section titled “Lỗi 1: MDXError - Could not parse import/exports”[@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.
Lỗi 2: Unexpected end of file
Section titled “Lỗi 2: Unexpected end of file”MDXError: Unexpected end of fileNguyên nhân: Dấu ngoặc nhọn { trong tables không được escape đúng cách.
Cách Fix
Section titled “Cách Fix”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:
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:
npm install starlight-markdown-blocksCấ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 |So sánh các component
Section titled “So sánh các component”| Tính năng | Svelte Component | starlight-markdown-blocks |
|---|---|---|
| Cài đặt | Cần Svelte integration | Cần plugin riêng |
| Props | Đầy đủ | Hạn chế |
| Styling | Tự do | Phải custom render |
| Build time | Chậm hơn | Nhanh hơn |
Kết luận
Section titled “Kết luận”- Khuyến nghị: Sử dụng
starlight-markdown-blockscho các custom blocks đơn giản - Tránh: Import Svelte components trực tiếp trong MDX frontmatter
- Lưu ý: Luôn escape
{và}thành{và}trong tables