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

fastify-swagger@3.5.0版本如何添加自定义CSS样式

解决方案
  • 前置操作:先将你的MyCSS.scss编译为纯CSS文件,比如命名为custom-swagger.css,可通过sass命令行工具或者项目内的构建流程完成编译,编译后内容如下:
.introduction .summary {
    text-shadow: 0in;
}
.code { 
    background-color: gray; 
    color: black; 
}

方式1:内联CSS内容(适合CSS量小的场景)

直接将编译后的CSS内容填入配置的uiConfig.customCss字段即可,修改后的完整配置如下:

const fs = require('fs')
const path = require('path')

// 读取编译后的CSS文件内容,CSS内容较少时也可以直接写在字符串里
const customCss = fs.readFileSync(path.join(__dirname, './custom-swagger.css'), 'utf8')

const swaggerConfig = {
    swagger: {
      info: {
        title: 'My swagger',
        description: `something`,
        version: '2.0.0'
      },
      externalDocs: {
        url: 'https://swagger.io',
        description: 'Find more info here'
      },
      schemes: [`${schema}`],
      consumes: ['application/json'],
      produces: ['application/json'],
      tags: [
        { name: 'tag1', description: 'desc1' },
        { name: 'tag2', description: 'desc2' },
      ],
      securityDefinitions: {
        Authorization_Token: {
            type: 'apiKey',
            name: 'Authorization',
            in: 'header'
        },
        User_Token: {
            type: 'apiKey',
            name: 'X-User-token',
            in: 'header'
        }
      }
    },
    // 新增uiConfig配置,和swagger字段平级即可
    uiConfig: {
      customCss: customCss
    },
    exposeRoute: true,
    routePrefix: `${constants.EXTERNAL_PATH}/api-docs`
};
fastify.register(require('fastify-swagger'), swaggerConfig);

方式2:引入独立CSS文件(适合CSS量大的场景)

  1. 先将编译后的custom-swagger.css放到你的fastify静态资源托管目录(比如public文件夹),确保可以通过/static/custom-swagger.css这类路径正常访问
  2. 修改配置的uiConfig.customCssUrl字段指向该CSS地址:
const swaggerConfig = {
    // 其他原有配置保持不变
    uiConfig: {
      customCssUrl: '/static/custom-swagger.css'
    },
    exposeRoute: true,
    routePrefix: `${constants.EXTERNAL_PATH}/api-docs`
};

注意事项

  • fastify-swagger 3.5.0版本原生支持customCss和customCssUrl两个配置项,无需额外安装依赖
  • uiConfig是和swagger、exposeRoute平级的顶层配置,不要写到swagger字段内部

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 22:45:03