同樣的 main.ts 的代碼,nest new 出來的一個初始項目就不會報錯,而我們有其他應用代碼的項目就會報錯。
import {NestFactory} from '@nestjs/core';
import {
SwaggerModule,
DocumentBuilder,
SwaggerCustomOptions,
} from '@nestjs/swagger';
import {AppModule} from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const config = new DocumentBuilder()
.setTitle('Cloud Native InceptionPad Basic')
.setDescription('The API description')
.setVersion('1.0')
.addBearerAuth()
.build();
const document = SwaggerModule.createDocument(app, config);
const customOptions: SwaggerCustomOptions = {
swaggerOptions: {
persistAuthorization: true,
},
customSiteTitle: 'InceptionPad API Docs',
};
SwaggerModule.setup('api', app, document, customOptions);
await app.listen(3000);
}
bootstrap();
下圖為 nest new 的新項目:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiNx8FesU2cfdGLwczX0xiRGZkRGZ0Xy9GbvNGLwIzXlpXazxSPrhUY2I1RilXOyQWQClGVF5UMR9Fd4VGdsATNfd3bkFGazxSUhxGatJGbwhFT1Y0Mk9VZwlHdssmch1mclRXY39CXldWYtlWPzNXZj9mcw1ycz9WL49zZuBnLhRDN5EDN5M2MjBTY4QGZ5czY1QjNyATN3IWZ3AjY3YzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
下圖為開發中的項目:
猜測
某個 module 導緻了 swagger 的報錯。于是,AppModule 的 imports 删掉,node 可以正常啟動了。
// app.module.ts
import {Module, MiddlewareConsumer} from '@nestjs/common';
import {AuthModule} from './_basic/_auth/_auth.module';
import {UserModule} from './_basic/_user/_user.module';
import {RoleModule} from './_basic/_role/_role.module';
import {HttpLoggerMiddleware} from './_basic/_logger/_http-logger.middleware';
@Module({
imports: [AuthModule, UserModule, RoleModule],
})
export class AppModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(HttpLoggerMiddleware).forRoutes('*');
}
}
然而,使用相同的 app.module.ts,将各個 module 逐個複制到新項目中,node 總是可以正常啟動的,說明各個 module 的代碼是沒有問題的。
對比工程檔案
由于開發中的項目用到了 gts,在 gts init 的時候,覆寫了 tsconfig.json 等幾個 nest 架構原有的配置檔案。逐個排查配置檔案,确定是由于 tsconfig.json 的覆寫導緻的報錯。