本機 Markdown
在執行階段從資料夾載入 Markdown 與 MDX 檔案。
@fumadocs/local-md 會從資料夾讀取 Markdown 與 MDX 檔案並在執行階段編譯,與其他內容來源一樣支援 frontmatter、meta 檔案及搜尋資料。
與 Astro 內容集合不同,它不會經過打包工具,因此:
- 圖片不會在建置時最佳化。
- MDX 檔案無法匯入模組,請改在算繪時傳入元件。
設定
npm install @fumadocs/local-md shiki建立來源,並透過 getSource() 取得它的載入器:
import { dynamicLoader } from 'fumadocs-core/source';
import { localMd } from '@fumadocs/local-md';
const docs = localMd({
dir: 'content/docs',
});
const docsLoader = dynamicLoader(docs.dynamicSource(), {
baseUrl: '/docs',
});
export async function getSource() {
return docsLoader.get();
}算繪頁面
page.data.load() 會編譯頁面並回傳對應的算繪器。
在頁面中將其序列化,再於 React island 中算繪:
---
import type { GetStaticPaths, InferGetStaticPropsType } from 'astro';
import Layout from '@/layouts/Layout.astro';
import { Docs } from '@/components/docs';
import { getSource } from '@/lib/source';
export const prerender = true;
export const getStaticPaths = (async () => {
const source = await getSource();
return source.getPages().map((page) => ({
params: { slug: decodeURI(page.slugs.join('/')) || undefined },
props: { page },
}));
}) satisfies GetStaticPaths;
type Props = InferGetStaticPropsType<typeof getStaticPaths>;
const { page } = Astro.props;
const source = await getSource();
const pageTree = await source.serializePageTree(source.getPageTree());
const { serialize } = await page.data.load();
---
<Layout title={page.data.title}>
<Docs
client:load
pathname={Astro.url.pathname}
params={Astro.params}
tree={pageTree}
title={page.data.title}
render={serialize()}
/>
</Layout>熱重載
開發期間,監看器會在內容檔案變更時通知來源。
請加入 Vite 外掛,並將您的來源連接到該外掛:
import { defineConfig } from 'astro/config';
import { localContentPlugin } from '@fumadocs/local-md/dev/vite';
export default defineConfig({
vite: {
// 內容變更後會重新載入瀏覽器,可使用 `{ reload: false }` 停用
plugins: [localContentPlugin()],
},
});設定
Markdown 與 MDX 檔案分別由不同的外掛編譯,因此兩種格式各有其選項:
import { localMd } from '@fumadocs/local-md';
import { pageSchema, metaSchema } from 'fumadocs-core/source/schema';
import remarkDirective from 'remark-directive';
const docs = localMd({
dir: 'content/docs',
// 驗證 frontmatter 與 meta 檔案
frontmatterSchema: pageSchema.extend({
// ...
}),
metaSchema: metaSchema.extend({
// ...
}),
// `.md` 檔案
mdOptions: {
// `<include>` 僅適用於 MDX,Markdown 請改用 `::include[./file.md]`
remarkPlugins: [remarkDirective],
},
// `.mdx` 檔案
mdxOptions: {
rehypeCodeOptions: {
themes: { light: 'github-light', dark: 'github-dark' },
},
},
});程式碼執行
MDX 檔案會透過 new Function 以 JavaScript 形式執行。請勿將不受信任的 MDX 檔案放在 dir 中。若執行環境不支援 eval() (例如 Cloudflare Workers) ,請改用 Markdown 檔案。
Markdown 檔案會直接從語法樹算繪,外掛產生的 JSX 則交由虛擬 JavaScript 引擎求值。
靜態來源
staticSource() 只會讀取檔案一次,不支援熱重載,因此直接使用一般的 loader() 即可:
import { loader } from 'fumadocs-core/source';
export const source = loader(await docs.staticSource(), {
baseUrl: '/docs',
});How is this guide?
最後更新於
