插件窝 干货文章 在Linux系统中Swagger UI如何自定义主题

在Linux系统中Swagger UI如何自定义主题

Swagger 定义 CSS 主题 178    来源:    2025-05-07

自定义 Swagger UI 主题 (Linux 环境)

Swagger UI 提供了多种自定义主题的方式,以下是在 Linux 系统中实现自定义主题的几种方法:

方法一:使用预构建的主题

  1. 下载预构建主题

    wget https://github.com/ostranme/swagger-ui-themes/archive/refs/heads/master.zip
    unzip master.zip
    
  2. 引入主题CSS: 在你的 Swagger UI HTML 文件中,替换默认的 CSS 文件:

    <link rel="stylesheet" href="path/to/swagger-ui-themes-master/themes/3.x/theme-material.css" />
    

    可用的预构建主题包括:theme-material.css, theme-monokai.css, theme-muted.css, theme-flattop.css, theme-newspaper.css

方法二:自定义 CSS 覆盖

  1. 创建自定义 CSS 文件

    mkdir -p /var/www/swagger/css
    nano /var/www/swagger/css/custom-theme.css
    
  2. 添加自定义样式

    /* 示例自定义样式 */
    .swagger-ui {
       font-family: "Open Sans", sans-serif;
    }
    
    .opblock-summary {
       background-color: #4a4a4a;
       color: white;
    }
    
    .topbar {
       background-color: #003366;
    }
    
  3. 在 HTML 中引入

    <link rel="stylesheet" href="css/custom-theme.css" />
    

方法三:使用 Swagger UI 插件系统

  1. 安装必要的 Node.js 工具

    sudo apt update
    sudo apt install nodejs npm
    npm install swagger-ui-themes
    
  2. 创建自定义主题文件

    const { SwaggerTheme } = require('swagger-themes');
    const theme = new SwaggerTheme();
    
    const darkStyle = theme.getBuffer('dark');
    // 将 darkStyle 写入文件或直接使用
    

方法四:修改 Swagger UI 源码

  1. 克隆 Swagger UI 仓库

    git clone https://github.com/swagger-api/swagger-ui.git
    cd swagger-ui
    npm install
    
  2. 修改 src/style/_variables.scss 文件中的变量值

  3. 重新构建

    npm run build
    

Nginx 配置示例

如果你通过 Nginx 提供 Swagger UI 服务,可以这样配置:

server {
    listen 80;
    server_name api.example.com;

    location / {
        root /var/www/swagger;
        index index.html;
    }

    location /css/ {
        alias /var/www/swagger/css/;
    }
}

验证自定义主题

  1. 重启你的 web 服务器:

    sudo systemctl restart nginx
    
  2. 访问你的 Swagger UI 页面,检查主题是否已应用

注意事项

  • 确保自定义 CSS 在默认 Swagger UI CSS 之后加载
  • 使用浏览器开发者工具检查元素以确定正确的 CSS 选择器
  • 考虑主题对不同 Swagger UI 版本的兼容性
  • 在生产环境部署前充分测试自定义主题

希望这些方法能帮助你在 Linux 系统中成功自定义 Swagger UI 主题!