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

如何在Docusaurus头部菜单展示侧边栏顶级分类标签

如何将Docusaurus侧边栏一级分类移至头部菜单

需求示例:
侧边栏一级分类移至头部菜单效果

完全可以实现,具体步骤如下:

1. 确认侧边栏配置结构

你的侧边栏配置一般在项目根目录的sidebars.js中,典型结构如下:

module.exports = {
  docs: [
    'introduction', // 单个文档类一级项
    {
      type: 'category',
      label: 'Category 1',
      items: ['category1/item1', 'category1/item2'],
    },
    {
      type: 'category',
      label: 'Category 2',
      items: ['category2/item1'],
    },
    // 更多一级分类...
  ],
};

2. 修改头部导航配置

打开docusaurus.config.js,按以下步骤调整:

步骤1:引入侧边栏配置

在文件顶部添加:

const sidebars = require('./sidebars');

步骤2:提取侧边栏一级分类数据

添加代码自动提取侧边栏的一级项(包含单个文档和分类):

// 提取侧边栏的一级导航项
const sidebarTopNavItems = sidebars.docs.map(item => {
  if (typeof item === 'string') {
    // 处理单个文档(比如Introduction)
    return {
      label: item.charAt(0).toUpperCase() + item.slice(1),
      to: `/docs/${item}`,
    };
  } else {
    // 处理分类项
    return {
      label: item.label,
      to: `/docs/${item.items[0]}`, // 跳转到分类下第一个文档
      // 如需给分类加下拉子菜单,取消下面注释:
      // items: item.items.map(subItem => ({
      //   label: subItem.split('/')[1],
      //   to: `/docs/${subItem}`,
      // }))
    };
  }
});

步骤3:合并到头部菜单

找到themeConfig.navbar.items,将提取出的sidebarTopNavItems合并进去:

themeConfig: {
  navbar: {
    title: '你的站点名称',
    items: [
      ...sidebarTopNavItems, // 把侧边栏一级分类放到头部
      // 保留原有头部项(比如GitHub链接等)
      {
        href: 'https://github.com/你的仓库地址',
        label: 'GitHub',
        position: 'right',
      },
    ],
  },
},

3. 验证效果

重启Docusaurus开发服务器(npm run start),即可看到侧边栏的一级分类已出现在头部菜单中。

如果是多语言站点,需额外处理标签的国际化,比如用i18n翻译键替换硬编码的标签文本。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 07:03:29