You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Docusaurus MDX中如何使用版本变量生成适配版本的外链

你之前的写法失效的核心原因:Markdown 链接的 URL 字段仅做纯文本解析,不会渲染内部嵌套的 React 组件,所以<Version>标签会直接被识别为普通字符串,无法得到预期的版本号。

以下是可落地的实现方案:

方案1:使用Docusaurus内置上下文自动获取版本号(推荐)

Docusaurus 本身提供了文档元数据的上下文钩子,不需要手动维护硬编码的版本组件,新增版本时会自动适配:

  1. 首先在项目src/components目录下创建通用版本化链接组件VersionedLink.jsx:
import React from 'react';
import { useDoc } from '@docusaurus/theme-common/internal';

export default function VersionedLink({ children, repoPath, ...props }) {
  const { metadata } = useDoc();
  // 未做版本控制的文档默认指向main分支,可根据需求调整
  const currentVersion = metadata.version ?? 'main';
  const finalHref = `https://github.com/seladb/my-project/blob/v${currentVersion}/${repoPath}`;
  return <a href={finalHref} target="_blank" rel="noopener noreferrer" {...props}>{children}</a>;
}
  1. 在MDX文件中直接调用组件即可:
import VersionedLink from '@site/src/components/VersionedLink';

请查看 <VersionedLink repoPath="file.js">对应代码文件</VersionedLink>

方案2:单页面直接拼接版本链接

如果仅需要在个别页面使用,无需封装组件,可以直接在MDX中获取版本号拼接链接:

import { useDoc } from '@docusaurus/theme-common/internal';

// 获取当前文档版本号
const { metadata } = useDoc();
const currentVersion = metadata.version ?? 'main';
const codeFileUrl = `https://github.com/seladb/my-project/blob/v${currentVersion}/file.js`;

// 渲染链接
请查看 <a href={codeFileUrl}>对应代码文件</a>

旧方案调整方法

如果你坚持使用自己编写的Version组件,需要调整为JSX写法渲染链接,不要用Markdown链接格式:

import {Version} from '/docs/Version'

// 正确写法
请查看 <a href={`https://github.com/seladb/my-project/blob/${Version()}/file.js`}>对应代码文件</a>

注意这种方式每次新建版本时都需要手动修改Version组件的返回值,维护成本较高,更推荐使用内置上下文的方案。

内容的提问来源于stack exchange,提问作者seladb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 15:24:05