Swagger UI是API文档可视化的强大工具,但在Linux环境下可能会遇到一些显示或性能问题。以下是一些优化Swagger UI展示效果的方法:
const ui = SwaggerUIBundle({
url: "your-api-docs.json",
dom_id: '#swagger-ui',
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout",
// 优化配置项
docExpansion: 'none', // 默认折叠所有操作
defaultModelsExpandDepth: -1, // 隐藏模型定义
displayOperationId: true, // 显示操作ID
filter: true, // 启用搜索过滤
showExtensions: true // 显示扩展信息
})
# 确保使用最新Swagger UI版本
npm update swagger-ui-dist
# 或
yarn upgrade swagger-ui-dist
创建自定义CSS文件覆盖默认样式:
/* custom-swagger.css */
.swagger-ui .topbar {
background-color: #2d3e50;
}
.swagger-ui .info .title {
color: #2d3e50;
}
.swagger-ui .opblock .opblock-summary-method {
font-weight: bold;
}
/* 响应式调整 */
@media (max-width: 768px) {
.swagger-ui .wrapper {
padding: 10px;
}
}
/* dark-theme.css */
.swagger-ui {
filter: invert(88%) hue-rotate(180deg);
}
.swagger-ui .scheme-container {
background-color: #1e1e1e;
}
在Nginx配置中添加:
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
location /swagger-ui/ {
expires 7d;
add_header Cache-Control "public";
}
使用Webpack或类似工具进行代码分割:
import(/* webpackChunkName: "swagger-ui" */ 'swagger-ui-dist/swagger-ui-bundle.js')
FROM nginx:alpine
# 使用多阶段构建减小镜像大小
COPY --from=build /app/dist /usr/share/nginx/html
# 优化Nginx配置
RUN echo "server_tokens off;" > /etc/nginx/conf.d/security.conf && \
echo "client_max_body_size 10m;" >> /etc/nginx/conf.d/security.conf
EXPOSE 80
resources:
limits:
cpu: "1"
memory: "512Mi"
requests:
cpu: "100m"
memory: "128Mi"
const ui = SwaggerUIBundle({
// ...其他配置
requestInterceptor: (req) => {
if (req.url.endsWith('/login')) {
req.headers['Authorization'] = 'Bearer ' + localStorage.getItem('jwt');
}
return req;
}
})
# 在OpenAPI规范中使用tags
tags:
- name: User
description: 用户相关操作
- name: Product
description: 产品管理
location /api/ {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
}
// 使用分块加载
const ui = SwaggerUIBundle({
url: "large-api-docs.json",
// 启用分块处理
jsonEditor: true,
// 或使用URL分片
urls: [
{url: "api-docs-part1.json", name: "基础API"},
{url: "api-docs-part2.json", name: "扩展API"}
]
})
通过以上优化方法,可以显著提升Linux环境下Swagger UI的展示效果和用户体验。根据实际需求选择适合的优化策略组合使用效果更佳。