NestJs Swagger 如何添加自定义图标

NestJs Swagger how to add custom favicon

我正在尝试将自定义图标添加到我的 NestJs 文档中。但是,我对如何解析路径文件有点迷茫,也不确定如何实现这一点。

我正在使用 nestjs/swagger 模块版本 3.1.0 并尝试在初始化 Swagger 模块时像这样传递路径文件。

我的main.ts文件

SwaggerModule.setup('/v1/docs', app, document, {
    customCss: CUSTOM_STYLE,
    customSiteTitle: 'My API Documentation',
    customfavIcon: './public/favicon.jpg'
});

搜索了 github 个问题,但没有找到任何有用的信息。正如您从代码中看到的那样,我能够修改 CSS 样式,但我不知道如何自定义图标。

感谢任何帮助

我已使用以下方法将自定义图标添加到我的 swagger 文档中:

您首先要确定的是,在您的 main.ts 中,应用程序初始化如下:

const app: NestExpressApplication = await NestFactory.create(...)

要提供静态内容,您必须使用 NestExpressApplication 初始化您的应用。

下一步是允许 Nest 应用程序在初始化后使用 main.ts 中的以下内容查找 public 内容:

app.useStaticAssets(join(__dirname, '..', 'public'));

此外,在应用程序的根目录中创建一个 public 目录,并将 favicon.jpg 文件粘贴到其中。

现在是时候在 main.ts

中初始化 Swagger
SwaggerModule.setup('/v1/docs', app, document, {
    customCss: CUSTOM_STYLE,
    customSiteTitle: 'My API Documentation',
    customfavIcon: '../favicon.jpg'
});

如果我们的 main.ts 位于应用程序根目录下的 src 文件夹中,您必须提供应用程序根目录的相对路径,例如 ../favicon.jpg

替代解决方案,只需托管您的网站图标并使用外部引用它 url

  SwaggerModule.setup('api', app, getSwaggerDocument(app), {
    ...
    customfavIcon:
      'https://[your-bucket-url].com/.../anything.png',
  });

为了重复 pravindot17 的回答,现在有 @nestjs/serve-static 包用于托管静态文件。这使我们远离 type-casting Nest.js 客户端并依赖于我们隐含的假设,即我们是 运行 一个 Express-backed Nest.js 服务器。

安装包后,将其挂接到 src/app.module.ts。此配置要求项目的根目录有一个 /public/ 文件夹,您可以在其中存储静态资产。

import { Module } from '@nestjs/common';
import { ServeStaticModule } from '@nestjs/serve-static';
import { join } from 'path';

@Module({
  imports: [
    // Host static files in ../public under the /static path.
    ServeStaticModule.forRoot({
      /**
       * Config options are documented:
       * https://github.com/nestjs/serve-static/blob/master/lib/interfaces/serve-static-options.interface.ts
       */
      rootPath: join(__dirname, '..', '..', 'public'),
      serveRoot: '/static',
    }),
    // ... 
})
export class AppModule {}

现在我自己的偏好是使用绝对路径而不是相对路径,因为它独立于我们选择用来托管 API 文档的路径。

SwaggerModule.setup('/v1/docs', app, document, {
    customfavIcon: '/static/favicon.jpg'
});

最后要注意的是,此配置托管来自 /static/* 的静态文件,这样做是为了防止 API 对 non-existing 端点的调用向 [=31] 显示错误消息=] 找不到静态文件。

否则,non-existing 端点上的所有 404 将类似于:

{"statusCode":404,"message":"ENOENT: no such file or directory, stat '/Users/me/my-project/public/index.html'"}