<p>通过修改 launch.json 文件中的 args 字段,可为 vscode 调试程序传递自定义启动参数,支持 node.js、python、C# 等语言,并可结合 ${workspaceFolder} 和 ${env:NAME} 等变量实现灵活配置。</p>

在使用 VSCode 进行开发时,经常需要为程序传递自定义启动参数。通过修改 launch.json 配置文件,可以轻松实现这一功能。以下是具体配置方法和常见场景说明。
1. 创建或编辑 launch.json
打开调试面板,点击“创建 launch.json”或直接编辑项目中 .vscode/launch.json 文件。确保配置的是正确的调试环境(如 node.js、Python、C# 等)。
示例:Node.js 项目的基本配置结构
{ "version": "0.2.0", "configurations": [ { "name": "启动应用", "type": "node", "request": "launch", "program": "${workspaceFolder}/app.js" } ] }
2. 添加自定义启动参数
使用 args 字段传入命令行参数。这些参数会在程序启动时作为 process.argv 的一部分传递。
示例:为 Node.js 程序添加参数
{ "name": "带参数启动", "type": "node", "request": "launch", "program": "${workspaceFolder}/app.js", "args": ["--env", "development", "--port", "3000"] }
在代码中可通过以下方式读取:
const args = process.argv.slice(2); console.log(args); // ['--env', 'development', '--port', '3000']
3. 支持动态变量和环境配置
VSCode 支持在 args 中使用变量,提升配置灵活性。
- ${workspaceFolder}:项目根路径
- ${env:NAME}:系统环境变量
示例:结合环境变量传参
"args": [ "--config", "${workspaceFolder}/config.json", "--log-level", "${env:LOG_LEVEL}" ]
运行前可在系统中设置:export LOG_LEVEL=debug(linux/macOS)或set LOG_LEVEL=debug(windows)
4. 不同语言的参数传递方式
不同运行环境配置略有差异,但核心逻辑一致。
Python 示例:
{ "name": "Python 脚本", "type": "python", "request": "launch", "program": "${workspaceFolder}/main.py", "args": ["input.txt", "--output", "result.json"] }
C# (.NET CLI) 示例:
{ "name": "C# 应用", "type": "coreclr", "request": "launch", "program": "${workspaceFolder}/bin/Debug/net6.0/app.dll", "args": ["--verbose", "true"] }
基本上就这些。只要找到对应语言的调试类型并正确使用 args 字段,就能灵活控制启动参数。注意检查拼写和路径引用,避免因小失大。


