如何在VSCode中为NPM启动任务设置子文件夹?
在Monorepo子目录中配置VSCode启动任务
核心思路
通过修改.vscode/tasks.json和.vscode/launch.json中的cwd字段,指定任务运行的子目录路径,同时确保前置任务也对应到正确的子目录。
具体配置步骤
1. 配置tasks.json(任务定义)
在项目根目录的.vscode文件夹下创建或修改tasks.json,为每个子项目的任务指定cwd:
{ "version": "2.0.0", "tasks": [ // 子项目1的启动任务 { "label": "subproject1: start", "type": "npm", "script": "start", "options": { "cwd": "${workspaceFolder}/subproject1" }, "isBackground": true, "problemMatcher": { "owner": "typescript", "pattern": "$tsc", "background": { "activeOnStart": true, "beginsPattern": "Compiling...", "endsPattern": "Compiled successfully." } } }, // 子项目1的测试任务 { "label": "subproject1: test", "type": "npm", "script": "test", "options": { "cwd": "${workspaceFolder}/subproject1" } }, // 子项目2的启动任务(同理) { "label": "subproject2: start", "type": "npm", "script": "start", "options": { "cwd": "${workspaceFolder}/subproject2" }, "isBackground": true, "problemMatcher": { "owner": "typescript", "pattern": "$tsc", "background": { "activeOnStart": true, "beginsPattern": "Compiling...", "endsPattern": "Compiled successfully." } } } ] }
2. 配置launch.json(调试启动)
同样在.vscode文件夹下修改launch.json,指定调试的目标子项目,并关联对应的前置任务:
{ "version": "0.2.0", "configurations": [ { "name": "Launch subproject1", "type": "chrome", "request": "launch", "url": "http://localhost:4200", "webRoot": "${workspaceFolder}/subproject1/src", "preLaunchTask": "subproject1: start" }, { "name": "Launch subproject2", "type": "chrome", "request": "launch", "url": "http://localhost:4201", "webRoot": "${workspaceFolder}/subproject2/src", "preLaunchTask": "subproject2: start" } ] }
关键说明
cwd字段:指定任务运行的工作目录,${workspaceFolder}是VSCode内置变量,代表当前打开的根目录,后面拼接子项目路径即可。- 前置任务关联:确保
launch.json中的preLaunchTask和tasks.json中对应子项目的任务标签完全一致。 - 端口冲突:如果多个Angular项目同时启动,记得在各自子项目的
angular.json中修改服务端口,避免冲突。
内容的提问来源于stack exchange,提问作者Cam
相关产品推荐
相关产品推荐

