Fumadocs

验证链接

确保您的链接正确。

设置

您可以使用 next-validate-link 来验证内容文件中的链接。

本指南主要针对 Fumadocs MDX,有关其他设置,请参阅 next-validate-link 的文档。

为 Bun 创建一个脚本:

./scripts/lint.ts
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

要在应用运行时之外访问 source 对象,您需要一个运行时加载器:

preload = ["./scripts/preload.ts"]

运行脚本以验证链接:

bun ./scripts/lint.ts

How is this guide?

Last updated on

On this page