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

Is there any way to set environment variables in Visual Studio Code?

1个答案

1

In Visual Studio Code, setting environment variables can be accomplished in several different ways, depending on your specific use case and requirements. Below, I will outline several common methods for setting environment variables:

1. Using .env Files

One common method is to use a .env file to store environment variables. This approach is typically implemented with the dotenv library, which loads environment variables defined in the .env file into your project code.

Steps are as follows:

  1. Create a .env file in the project root directory.
  2. Add environment variables to the .env file, for example:
shell
DB_HOST=localhost DB_USER=root DB_PASS=s1mpl3
  1. In your code, use the dotenv library to load these variables:
javascript
require('dotenv').config(); console.log(process.env.DB_HOST); // Outputs 'localhost'

2. Setting Environment Variables in the VS Code Terminal

If you need to temporarily set environment variables within the Visual Studio Code development environment, you can configure them directly in the VS Code terminal.

For example, on Windows:

bash
set DB_HOST=localhost

On macOS or Linux:

bash
export DB_HOST=localhost

Then run your program in the terminal, which will use these environment variables.

3. Configuring Environment Variables in launch.json

When using Visual Studio Code's debugging feature, you can specify environment variables in the .vscode/launch.json file of your project.

For example:

json
{ "version": "0.2.0", "configurations": [ { "type": "node", "request": "launch", "name": "Launch Program", "skipFiles": [ "<node_internals>/**" ], "program": "${workspaceFolder}/app.js", "env": { "DB_HOST": "localhost", "DB_USER": "root", "DB_PASS": "s1mpl3" } } ] }

After this setup, these environment variables will be automatically applied whenever you start the program using VS Code's debugging feature.

These three methods each offer distinct advantages and are suitable for different scenarios. The choice of method depends on your specific requirements and project setup.

2024年10月26日 11:18 回复

你的答案