VSCode自动创建终端运行脚本方法

在 VS Code 中,可以通过配置 tasks.json 来自动创建多个终端并运行命令。以下是具体步骤:

方法 1:使用 VS Code 任务(tasks.json)

  1. 创建任务配置
    打开命令面板(Ctrl+Shift+P),输入 **”Tasks: Configure Task”**,选择 **”Create tasks.json file from template”**,然后选择 **”Others”**。

  2. 编辑 tasks.json
    修改文件如下,假设需要启动两个服务:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    {
    "version": "2.0.0",
    "tasks": [
    {
    "label": "启动服务1",
    "type": "shell",
    "command": "npm run dev",
    "presentation": {
    "panel": "new", // 新终端面板
    "focus": true // 可选:聚焦到该终端
    }
    },
    {
    "label": "启动服务2",
    "type": "shell",
    "command": "npm run start", // 替换为你的第二个命令
    "presentation": {
    "panel": "new"
    }
    },
    {
    "label": "并行启动所有服务",
    "dependsOn": ["启动服务1", "启动服务2"],
    "dependsOrder": "parallel" // 并行执行依赖任务
    }
    ]
    }
  3. 运行任务

    • 打开命令面板,输入 **”Tasks: Run Task”**。
    • 选择 **”并行启动所有服务”**,VS Code 会创建两个终端并分别执行命令。

如果运行脚本不在相同目录,可以使用options指定目录:

1
2
3
4
5
6
7
8
9
10
11
{
"label": "运行数据库",
"type": "shell",
"command": "npm run dev",
"options": {
"cwd": "${workspaceFolder}/../../memeryDBCenter" // 直接指定工作目录
},
"presentation": {
"panel": "new"
}
}

在 VS Code 的 tasks.json 中,如果需要任务按顺序执行(而非并行),可以通过以下两种方式配置:
直接明确指定依赖任务的执行顺序:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
{
"version": "2.0.0",
"tasks": [
{
"label": "运行数据库",
"type": "shell",
"command": "cd ../../memeryDBCenter && npm run dev",
"presentation": {
"panel": "new"
}
},
{
"label": "运行主项目",
"type": "shell",
"command": "npm run prj",
"presentation": {
"panel": "new"
}
},
{
"label": "顺序启动所有服务",
"dependsOn": ["运行数据库", "运行主项目"],
"dependsOrder": "sequential" // 顺序执行依赖任务(默认行为)
}
]
}
如果 运行数据库 是持续运行的服务(如 npm run dev 启动的服务器),它将不会自动结束,导致后续任务 运行主项目 无法执行。

解决方案:仅对非阻塞任务使用顺序执行。若需同时运行多个服务,应保持 parallel 模式。

如果需要平行运行,但有时间滞后,需要从代码层面解决,比如下面的代码引入重试机制:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
    const axios = require('axios');

async function fetchWithRetry(url, maxRetries = 5, baseDelay = 1000) {
let attempt = 0;
while (true) {
try {
const response = await axios.get(url);
return response.data;
} catch (error) {
if (attempt >= maxRetries) {
throw new Error(`请求失败,已重试 ${maxRetries} 次: ${error.message}`);
}
const delay = baseDelay * Math.pow(2, attempt);
console.log(`请求失败,${delay}毫秒后第 ${attempt + 1} 次重试...`);
await new Promise(resolve => setTimeout(resolve, delay));
attempt++;
}
}
}

// 使用示例
try {
const dbconfig = await fetchWithRetry(config.memoryDBCenterUri);
// 后续处理逻辑...
} catch (error) {
console.error('所有重试失败:', error.message);
process.exit(1);
}