Swagger于Linux环境下的样式定制方法
在Linux系统上定制Swagger样式前,需先获取Swagger UI的资源文件。常见方式有两种:
npm install swagger-ui-dist(或yarn add swagger-ui-dist)下载Swagger UI的预编译资源,资源会存放在项目的node_modules/swagger-ui-dist目录下。docker pull swaggerapi/swagger-ui:v4.15.5(版本号可根据需求调整),然后运行docker run -d -p 38081:8080 swaggerapi/swagger-ui:v4.15.5,容器会暴露Swagger UI的Web界面(默认地址为http://<服务器IP>:38081/swagger-ui/index.html)。通过编写自定义CSS文件覆盖Swagger UI的默认样式,是最灵活且不影响源码的方法。
custom.css(或其他名称),编写样式规则。例如:/* 修改顶部导航栏背景色 */
.swagger-ui .topbar {
background-color: #007bff !important;
}
/* 修改API标题颜色和字体大小 */
.swagger-ui .info .title {
color: #333 !important;
font-size: 24px !important;
}
/* 修改文档背景色 */
.swagger-ui {
background-color: #f8f9fa !important;
}
上述示例中,!important用于提升样式优先级,确保覆盖默认样式。<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="node_modules/swagger-ui-dist/swagger-ui.css">
<link rel="stylesheet" href="./custom.css"> <!-- 自定义CSS -->
</head>
<body>
<div id="swagger-ui"></div>
<script src="node_modules/swagger-ui-dist/swagger-ui-bundle.js"></script>
<script src="node_modules/swagger-ui-dist/swagger-ui-standalone-preset.js"></script>
<script>
window.onload = function() {
SwaggerUIBundle({
url: "your-api-spec.json",
dom_id: '#swagger-ui',
presets: [SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset]
});
};
</script>
</body>
</html>
dist目录(默认路径为/usr/local/src/swagger-ui/dist),或在index.html中直接引入自定义CSS的路径。若不想手动编写CSS,可使用第三方主题库简化流程。例如:
git clone https://github.com/chfree/think-swagger-ui-vuele.git;cd think-swagger-ui-vuele && npm install;npm run dev;src/config/theme.js),调整颜色、字体等参数;若需要彻底修改UI结构或功能,可直接修改Swagger UI的源码。步骤如下:
git clone https://github.com/swagger-api/swagger-ui.git;src/core或src/style目录下的源码文件(如topbar.js、topbar.css);npm install安装依赖,再执行npm run build编译项目,将生成的dist目录部署到Linux服务器上。部分工具或框架提供了配置文件或插件,简化Swagger样式的定制。例如:
npm install swagger-ui-theme,然后运行swagger-ui-theme --theme-id my-custom-theme,按照提示配置主题参数(如主色调、字体等)。!important提升优先级,避免被默认样式覆盖;