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量大的场景)
- 先将编译后的
custom-swagger.css放到你的fastify静态资源托管目录(比如public文件夹),确保可以通过/static/custom-swagger.css这类路径正常访问 - 修改配置的
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
相关产品推荐
相关产品推荐

