乐闻世界logo
搜索文章和话题

How do I add environment variables to launch.json in VSCode

1个答案

1

In Visual Studio Code (VSCode), you can add environment variables by modifying the launch.json file in your workspace, which is commonly used for configuring debugging settings. The following steps and examples will guide you through adding and configuring environment variables for your application.

Step 1: Open Workspace Settings

First, ensure that you have the correct project folder open in VSCode.

Step 2: Access the launch.json File

  • Use the shortcut Ctrl+Shift+D to open the Debug view.
  • In the top Debug toolbar, click the gear icon (Configure) and select 'Add Configuration...'. VSCode will automatically create a launch.json file for you (if it doesn't already exist).

Step 3: Add Environment Variables

In the launch.json file, you can add configuration entries for different debugging environments. To add environment variables, specify them in the env property. For example, if you're using Node.js, your configuration might look like this:

json
{ "version": "0.2.0", "configurations": [ { "type": "node", "request": "launch", "name": "Launch Program", "skipFiles": ["<node_internals>/**"], "program": "${workspaceFolder}/app.js", "env": { "API_KEY": "123456", "ANOTHER_VAR": "abcdef" } } ] }

In this example, the env object contains two environment variables, API_KEY and ANOTHER_VAR, set to '123456' and 'abcdef' respectively.

Step 4: Save and Debug

Save the launch.json file and start a debugging session; VSCode will run your application using the environment variables you've set.

Notes

  • Ensure that your environment variable names and values are accurate; incorrect variables may cause your application to run abnormally.
  • If you modify environment variables, you need to restart the debugging session to apply the new settings.

By doing this, you can flexibly set specific environment variables for different debugging configurations, which helps simulate various runtime environments. This is particularly useful when developing and testing multi-environment configurations.

2024年6月29日 12:07 回复

你的答案