验证链接
确保你的链接是正确的。
安装
🌐 Setup
你可以使用 next-validate-link 来验证内容文件中的链接。
🌐 You can use next-validate-link to validate your links in content files.
本指南主要针对 Fumadocs MDX,其他设置请参阅 next-validate-link 的文档。
创建一个脚本:
🌐 Create a script:
import { type FileObject, printErrors, scanURLs, validateFiles } from 'next-validate-link';
import type { InferPageType } from 'fumadocs-core/source';
import { source } from '@/lib/source';
async function checkLinks() {
const scanned = await scanURLs({
// pick a preset for your React framework
preset: 'next',
populate: {
'docs/[[...slug]]': source.getPages().map((page) => {
return {
value: {
slug: page.slugs,
},
hashes: getHeadings(page),
};
}),
},
});
printErrors(
await validateFiles(await getFiles(), {
scanned,
// check `href` attributes in different MDX components
markdown: {
components: {
Card: { attributes: ['href'] },
},
},
// check relative paths
checkRelativePaths: 'as-url',
}),
true,
);
}
function getHeadings({ data }: InferPageType<typeof source>): string[] {
return data.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);
}
void checkLinks();运行 Lint
🌐 Running Lint
要在应用运行时之外访问 source 对象,请先配置 Fumadocs MDX Loader。
🌐 To access the source object outside of app runtime, configure Fumadocs MDX Loader first.
然后,运行脚本以验证链接:
🌐 Then, run the script to validate links:
bun ./scripts/lint.ts对于 Node.js,你可能需要配置 tsconfig-paths、TypeScript 转译,以及 Fumadocs MDX Loader。
除非有特殊原因,否则使用 Bun 或 tsx 会更简单。
Last updated on
