驗證連結
確保您的連結正確無誤。
設定
您可以使用 next-validate-link 驗證內容檔案中的連結。
本指南主要以 Fumadocs MDX 為主,其他設定方式請參閱 next-validate-link 的文件。
建立一個指令碼來掃描應用程式的路由,並透過 populate 列出文件路由的參數:
import { type FileObject, printErrors, scanURLs, validateFiles } from 'next-validate-link';
import { source } from '@/lib/source';
import routes from '../app/routes';
const scanned = await scanURLs({
preset: 'react-router',
routerConfig: routes,
populate: {
// async 集合會在載入內容時一併載入目錄
'docs/[[...splat]]': await Promise.all(
source.getPages().map(async (page) => ({
value: { splat: page.slugs },
hashes: getHeadings(await page.data.load()),
})),
),
},
});接著在同一個指令碼中,以掃描到的 URL 驗證您的內容檔案:
import type { TOCItemType } from 'fumadocs-core/toc';
printErrors(
await validateFiles(await getFiles(), {
scanned,
// 檢查各種 MDX 元件中的 `href` 屬性
markdown: {
components: {
Card: { attributes: ['href'] },
},
},
// 檢查相對路徑
checkRelativePaths: 'as-url',
}),
true,
);
function getHeadings({ toc }: { toc: TOCItemType[] }): string[] {
return toc.map((item) => item.url.slice(1));
}
function getFiles() {
const promises = source.getPages().map(async (page): Promise<FileObject> => ({
path: page.absolutePath,
content: await page.data.getText('raw'),
url: page.url,
data: page.data,
}));
return Promise.all(promises);
}執行 Lint
若要在應用程式執行階段之外存取 source 物件,請為 Bun 設定 Fumadocs MDX 載入器。
接著,執行指令碼來驗證連結:
bun ./scripts/lint.tsNode.js 載入器
您可能需要設定 TypeScript 轉譯 (或改用較新版本的 Node.js) ,以及 Fumadocs MDX 載入器。
若無特殊需求,直接使用 Bun 或 tsx 會比較簡單。
How is this guide?
最後更新於
