patch-spec:webpack: true 的手动替代方案
如果不想加编译器插件,可以改为在构建时手动应用 docs 文件。
优先用 CLI 插件,除非你有理由不这么做
CLI 插件在每次构建时都会自动做同样的事。如果你不想加编译器插件(比如构建管线不是 Nest CLI,或者对编译期间能运行什么有更严格的策略),可以改用下面的 patch-spec。
为什么需要这个
当 nest-cli.json 中设置了 "webpack": true(这是官方文档为多应用 monorepo 推荐的默认配置)时,DocfyModule 的运行时发现机制不会生效:webpack 会把一切打包进一个单独的 bundle,从不会像每个原始源文件对应一条记录那样填充 require.cache,而那个发现机制正依赖这一点。这是架构层面的限制,不是一个能修的 bug。见strict 模式与 webpack。
流程
bash
# 1. 先启动应用,只是为了拿到实时的 /api-json
node dist/main.js &
# 2. 生成一份已经应用好所有 docs 文件的 OpenAPI 文档
npx nestjs-docfy patch-spec --spec http://localhost:3000/api-json --out openapi.patched.json
# 3. 通过 DocfyUiModule 提供这份打过补丁的文档
# DocfyUiModule.setup('/docs', app, { staticSpecPath: './openapi.patched.json' });在 SwaggerModule.setup() 之前调用 DocfyUiModule.setup(),这样静态的 /api-json 会优先于实时的那份生效。
ts
// main.ts
DocfyUiModule.setup('/docs', app, { staticSpecPath: './openapi.patched.json' });
SwaggerModule.setup('api', app, document);选项
bash
npx nestjs-docfy patch-spec --spec <path-or-url> [options]| Option | Default | Description |
|---|---|---|
--spec <path|url> | (required) | A local openapi.json, or a URL (e.g. a running app's /api-json) |
--out <path> | stdout | Where to write the patched document |
--root <path> | . | Project root directory |
--tsconfig <path> | auto-detected | Path to tsconfig.json |
--pattern <glob> | **/*.controller.ts | Glob pattern to find controllers |
--format <format> | ts | Docs file format to look for: ts or js |
--quiet | false | Suppress all output except errors |
在 CI 中
.github/workflows/patch-spec.yml
# .github/workflows/patch-spec.yml
- name: Build patched OpenAPI document
run: |
node dist/main.js &
sleep 2
npx nestjs-docfy patch-spec --spec http://localhost:3000/api-json --out openapi.patched.json