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

如何为Docusaurus OpenAPI生成文件添加index.html后缀?

解决Docusaurus链接添加index.html后缀的方法

因为CDN/对象存储需要明确指向index.html文件,而Docusaurus默认生成的链接不带该后缀,以下是两种可行方案:

方案一:自定义主题覆盖Link组件

通过修改Docusaurus的链接生成逻辑,让所有内部链接自动添加index.html后缀:

  1. 在项目根目录创建src/theme文件夹,新建Link.js文件,内容如下:
import OriginalLink from '@docusaurus/theme-classic/lib/theme/Link';
import { useBaseUrlUtils } from '@docusaurus/useBaseUrl';

export default function Link(props) {
  const { withBaseUrl } = useBaseUrlUtils();
  let to = props.to;
  
  // 仅处理内部路径、非锚点、非.html结尾的链接
  if (to && !to.startsWith('http') && !to.startsWith('#') && !to.endsWith('.html')) {
    to = `${to}/index.html`;
  }
  
  return <OriginalLink {...props} to={withBaseUrl(to)} />;
}
  1. 在docusaurus.config.js中配置自定义主题,确保它在官方主题之前加载:
module.exports = {
  // ...其他配置项
  themes: [
    './src/theme',
    '@docusaurus/theme-classic',
  ],
};

重新构建项目后,所有通过内置Link组件生成的导航、文档链接都会自动带上index.html后缀。

方案二:构建后脚本批量替换链接

如果不想修改主题,可以在构建完成后用脚本批量替换所有HTML文件中的链接:

  1. 在项目根目录创建scripts/replace-href.js文件,内容如下:
const fs = require('fs');
const path = require('path');

const buildDir = './build'; // Docusaurus默认构建输出目录

// 替换单个HTML文件中的链接
function replaceHrefInFile(filePath) {
  let content = fs.readFileSync(filePath, 'utf8');
  // 匹配所有内部路径(以/开头)、非.html结尾的href,添加index.html后缀
  content = content.replace(/href="(\/[^"]+)(?<!\.html)"/g, 'href="$1/index.html"');
  fs.writeFileSync(filePath, content, 'utf8');
}

// 遍历构建目录下所有HTML文件
function traverseDir(dir) {
  const files = fs.readdirSync(dir);
  for (const file of files) {
    const fullPath = path.join(dir, file);
    const stat = fs.statSync(fullPath);
    if (stat.isDirectory()) {
      traverseDir(fullPath);
    } else if (path.extname(fullPath) === '.html') {
      replaceHrefInFile(fullPath);
    }
  }
}

traverseDir(buildDir);
  1. 在package.json的scripts中添加postbuild命令,让构建完成后自动执行脚本:
{
  "scripts": {
    // ...其他脚本
    "postbuild": "node ./scripts/replace-href.js"
  }
}

执行npm run build后,脚本会自动遍历所有构建生成的HTML文件,将符合条件的链接替换为带index.html后缀的路径。

注意:如果你的项目有特殊路径规则,可以根据需求调整脚本中的正则表达式,避免误替换。

内容的提问来源于stack exchange,提问作者this is not my name

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 10:16:21