You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现NestJS/Swagger应用启动后自动打开浏览器?

问题

我希望NestJS/Swagger应用在bootstrap执行完成后自动启动并打开浏览器。最初我考虑使用app.listen的回调函数实现,示例代码如下:

async function bootstrap(): Promise<void> {
    console.clear();
    console.log("Starting and validating");

    const app = await NestFactory.create<NestExpressApplication>(AppModule, {
        cors: true,
    });

    await app.listen(PORT, () => someOpenBrowserFuncion("/docs"));
}
bootstrap();

但未找到对应的实现方法。联想到React应用编译完成后会自动打开默认浏览器,且可通过以下脚本配置禁用该功能:

"scripts": {
  "start": "env BROWSER=none react-scripts start",
  "build": "react-scripts build",
  "test": "react-scripts test",
  "eject": "react-scripts eject"
},

请问NestJS/Swagger框架是否有类似的功能?比如通过如下脚本配置实现:

"scripts": {
  "build": "nest build",
  "dev": "nest start --watch",
  "start": "env BROWSER=true nest start",
  "production": "node dist/main",

},

或者是否有指定端点来启动浏览器的配置?


解答

NestJS本身并没有像React那样内置BROWSER环境变量的自动浏览器打开功能,直接用env BROWSER=true nest start无法实现需求。不过可以通过以下两种方式实现自动打开浏览器:

方式一:在Bootstrap代码中集成

借助第三方库open来实现,步骤如下:

  1. 安装依赖:
npm install open --save-dev
# 或
yarn add open -D
  1. 修改main.ts的bootstrap函数,确保服务启动完成后再打开浏览器:
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import open from 'open';

const PORT = process.env.PORT || 3000;

async function bootstrap(): Promise<void> {
    console.clear();
    console.log("Starting and validating");

    const app = await NestFactory.create<NestExpressApplication>(AppModule, {
        cors: true,
    });

    // 先启动服务,确认服务运行后打开Swagger文档页面
    await app.listen(PORT);
    console.log(`Application is running on: http://localhost:${PORT}`);
    await open(`http://localhost:${PORT}/docs`);
}
bootstrap();

如果需要仅在开发环境打开浏览器,可增加环境判断:

if (process.env.NODE_ENV === 'development') {
    await open(`http://localhost:${PORT}/docs`);
}

方式二:通过package.json脚本配置

如果不想修改代码,可以借助wait-on(等待服务启动)和open-cli(命令行打开浏览器)工具实现:

  1. 安装依赖:
npm install wait-on open-cli --save-dev
# 或
yarn add wait-on open-cli -D
  1. 修改package.json的scripts:
"scripts": {
  "build": "nest build",
  "dev": "concurrently \"nest start --watch\" \"wait-on http://localhost:3000 && open-cli http://localhost:3000/docs\"",
  "start": "concurrently \"nest start\" \"wait-on http://localhost:3000 && open-cli http://localhost:3000/docs\"",
  "production": "concurrently \"node dist/main\" \"wait-on http://localhost:3000 && open-cli http://localhost:3000/docs\""
}

这里用concurrently同时执行服务启动和等待逻辑,wait-on会检测服务端口是否可用,避免浏览器提前打开出现404问题。


内容的提问来源于stack exchange,提问作者Malkavianson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 03:20:25