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

如何在VS Code中打开多个集成终端并自动运行指定命令?

一键自动化React开发环境(多终端拆分显示)

完全可以实现!下面提供两种实用方案,既能自动启动三个任务,还能让它们在VS Code终端面板里拆分显示,不用手动折腾终端:

方案一:VS Code任务配置 + npm脚本

1. 整理npm脚本(可选但更清晰)

在项目的package.json里把三个命令单独封装,方便后续调用:

{
  "scripts": {
    "start": "react-scripts start", // 保留原React启动命令
    "tsc:watch": "tsc -w",
    "sass:watch": "sass src/sass:src/dist"
  }
}

2. 配置VS Code的tasks.json

按Ctrl+Shift+B打开任务面板,选择「创建tasks.json文件」,选「Others」模板,然后替换成以下配置:

{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "启动开发环境",
      "dependsOn": ["启动React服务", "监听TS变更", "编译Sass"],
      // 可选:打开项目时自动触发,不需要就删掉这行
      "runOptions": { "runOn": "folderOpen" }
    },
    {
      "label": "启动React服务",
      "type": "shell",
      "command": "npm run start",
      "presentation": {
        "group": "dev-group",
        "panel": "shared",
        "split": "right"
      },
      "isBackground": true,
      "problemMatcher": {
        "background": {
          "activeOnStart": true,
          "beginsPattern": "Starting the development server",
          "endsPattern": "Compiled successfully"
        }
      }
    },
    {
      "label": "监听TS变更",
      "type": "shell",
      "command": "npm run tsc:watch",
      "presentation": {
        "group": "dev-group",
        "panel": "shared",
        "split": "down"
      },
      "isBackground": true,
      "problemMatcher": {
        "background": {
          "activeOnStart": true,
          "beginsPattern": "Watching for file changes",
          "endsPattern": "^$"
        }
      }
    },
    {
      "label": "编译Sass",
      "type": "shell",
      "command": "npm run sass:watch",
      "presentation": {
        "group": "dev-group",
        "panel": "shared",
        "split": "down"
      },
      "isBackground": true,
      "problemMatcher": {
        "background": {
          "activeOnStart": true,
          "beginsPattern": "Compiled",
          "endsPattern": "^$"
        }
      }
    }
  ]
}
  • dependsOn:让主任务一次性触发三个子任务
  • presentation.group:把三个终端归为一组,VS Code会自动拆分面板显示(横向+纵向拆分,布局清晰)
  • isBackground:让任务在后台运行,不会阻塞VS Code操作

配置好后,按Ctrl+Shift+B,选择「启动开发环境」,就能一键打开三个拆分的终端,各自运行对应的命令。

方案二:绑定快捷键一键触发

如果不想每次打开任务面板选,给主任务绑定快捷键更高效:

  1. 按Ctrl+K Ctrl+S打开键盘快捷设置
  2. 搜索「tasks.runTask」,点击「添加键绑定」
  3. 在弹出的settings.json中添加:
{
  "key": "ctrl+shift+d", // 自定义快捷键,换成你顺手的组合即可
  "command": "tasks.runTask",
  "args": "启动开发环境"
}

之后按下快捷键,就能直接启动所有拆分好的终端。

补充:单终端同时运行所有命令(可选)

如果不需要拆分终端,只是想同时运行三个命令,可以用concurrently包:

  1. 安装依赖:npm install --save-dev concurrently
  2. 在package.json里加脚本:
{
  "scripts": {
    "dev": "concurrently \"npm start\" \"npm run tsc:watch\" \"npm run sass:watch\""
  }
}

运行npm run dev就能在一个终端里看到三个命令的输出,但不如拆分终端直观,适合不需要单独查看每个日志的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 00:15:44