134

How can I set up environment variables in Visual Studio Code?

starball
  • 20,030
  • 7
  • 43
  • 238
Shakti Kumar Das
  • 1,365
  • 2
  • 9
  • 4

11 Answers11

112

Assuming you mean for a debugging session(?) then you can include a env property in your launch configuration.

If you open the .vscode/launch.json file in your workspace or select Debug > Open Configurations then you should see a set of launch configurations for debugging your code. You can then add to it an env property with a dictionary of string:string.

Here is an example for an ASP.NET Core app from their standard web template setting the ASPNETCORE_ENVIRONMENT to Development :

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": ".NET Core Launch (web)",
      "type": "coreclr",
      "request": "launch",
      "preLaunchTask": "build",
      // If you have changed target frameworks, make sure to update the program path.
      "program": "${workspaceFolder}/bin/Debug/netcoreapp2.0/vscode-env.dll",
      "args": [],
      "cwd": "${workspaceFolder}",
      "stopAtEntry": false,
      "internalConsoleOptions": "openOnSessionStart",
      "launchBrowser": {
        "enabled": true,
        "args": "${auto-detect-url}",
        "windows": {
          "command": "cmd.exe",
          "args": "/C start ${auto-detect-url}"
        },
        "osx": {
          "command": "open"
        },
        "linux": {
          "command": "xdg-open"
        }
      },
      "env": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "sourceFileMap": {
        "/Views": "${workspaceFolder}/Views"
      }
    },
    {
      "name": ".NET Core Attach",
      "type": "coreclr",
      "request": "attach",
      "processId": "${command:pickProcess}"
    }
  ]
}

KyleMit
  • 30,350
  • 66
  • 462
  • 664
Stewart_R
  • 13,764
  • 11
  • 60
  • 106
  • 2
    Thanks for your answer. I'm working on a node application and there using some environment variable like as process.env.VAR_NAME, I want the variables when running the project. Is the configuration env variables will be available in this case? It's not working. – Shakti Kumar Das Feb 06 '18 at 11:23
  • 1
    the above example sets an env variable when using a debugger from vscode (it works for the node debugger when launched from vscode too). Perhaps you could ask another question with some more details as to what exactly is not working? Are you running from vscode? Perhaps share the launch.json you are using? Does it run but just not have the env variable set or does it not run at all? If you want to tag me in a comment (just use @stewart_r in the comment) I'd be happy to try to help but I'm sure if you give a detailed enough question there will be lots of help available from others too. – Stewart_R Feb 06 '18 at 12:53
  • I feel I have answered the question as it was asked. If you are still struggling perhaps ask a new question trying, as far as possible, to follow this guide: https://stackoverflow.com/help/how-to-ask to give the community the best possible chance of being able to help – Stewart_R Feb 06 '18 at 12:55
  • Thank you for posting your answer, @Stewart_R. I feel it should be the accepted answer, and feature right at the top. – RAM Apr 02 '19 at 09:53
57

In the VSCode launch.json you can use "env" and configure all your environment variables there:

{
    "version": "0.2.0",
    "configurations": [
        {           
            "env": {
                "NODE_ENV": "development",
                "port":"1337"
            },
            ...
        }
    ]
}
Beachhouse
  • 4,972
  • 3
  • 25
  • 39
Petro Franko
  • 5,603
  • 1
  • 17
  • 18
  • What if I have two configurations? How do I switch between them? For example, the second one's name is "Launch Program 2". My code just imports an environment variable, but I want it to import different values depending on the current configuration. I mean just for a simple launch, I am NOT in a debugging session. – Sergey Zakharov Nov 19 '19 at 09:48
  • @SergeyZakharov within the "configurations" you can add a new one (just change the "name") and then select in debug tab which config you would like to use. – Petro Franko Dec 17 '19 at 14:43
55

You can load an environment file by setting the envFile property like this:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Launch",
      "type": "go",
      "request": "launch", 
      "mode": "debug",
      "remotePath": "",
      "port": 2345,
      "host": "127.0.0.1",
      "program": "${workspaceFolder}",
      "envFile": "${workspaceFolder}/.env",
      "args": [], 
      "showLog": true
    }
  ]
}

Place the .env file in your folder and add vars like this:

KEY1="TEXT_VAL1"
KEY2='{"key1":val1","key2":"val2"}'

Further Reading: Debugging go in vscode with environment variables

KyleMit
  • 30,350
  • 66
  • 462
  • 664
Mark
  • 842
  • 8
  • 11
19

I run vscode from my command line by navigating to the folder with the code and running

code .

If you do that all your bash/zsh variables are passed into vs code. You can update your .bashrc/.zshrc file or just do

export KEY=value

before opening it.

mvndaai
  • 3,453
  • 3
  • 30
  • 34
5

For C/C++ debugging this works for me (docs):

// Defined per configuration in launch.json
"environment": [
    {
        "name": "<env_name>",
        "value": "<env_value>"
    }
]
Daniel Fischer
  • 161
  • 2
  • 2
4

Could they make it any harder? Here's what I did: open system properties, click on advanced, add the environment variable, shut down visual studio and start it up again.

nmishr
  • 287
  • 3
  • 6
  • 1
    I believe the original post request to ask to set environment variables in the IDE is because he did not want to do that in the system. One possible reason could be that he did not have administrator right to change the system's environment variable – Nick Wills Nov 24 '20 at 14:08
  • The dialog that you use to set system environment variables also will let you set user environment variables (no elevation needed) that will be available for any new processes in the user's session. It works, but this is not an ideal way to set environment variables for VSCode for more than the debugger/launch.json uses. I prefer the approach recommended by @mvndaai: https://stackoverflow.com/a/60403290/100596 – Alan McBee Aug 20 '21 at 18:13
3

My response is fairly late. I faced the same problem. I am on Windows 10. This is what I did:

  • Open a new Command prompt (CMD.EXE)
  • Set the environment variables . set myvar1=myvalue1
  • Launch VS Code from that Command prompt by typing code and then press ENTER
  • VS code was launched and it inherited all the custom variables that I had set in the parent CMD window

Optionally, you can also use the Control Panel -> System properties window to set the variables on a more permanent basis

Hope this helps.

Sau001
  • 1,451
  • 1
  • 18
  • 25
  • 1
    I like your answer. But is it also possible to define environment variables in vscode. I know it is possible to do that for the terminals in the vscode, but I want it to be recognized by any vscode extensions as well. I believe your method did achieve what I want, but wonder if vscode has any setting that can do the same things. – Nick Wills Oct 09 '20 at 02:05
  • Close all instances of VS Code when attempting this. A running instance will merely spawn a new window and close the process you spawned. – Brent Nov 04 '20 at 17:29
  • @Bruce You're right, but I have not found defining those debug configs and environment files easy nor have I even got them to work reliably (nor do I have the time or desire to figure out yet another config format), while this way (and the equivalent in Mac/Linux) just works. – Benjamin R May 06 '21 at 08:24
1

For the VS Code process

VS Code's environment (the environment variables it has) will be its environment as it was given when it was created (see also Changing environment variable of a running process. TL;DR you generally can't change a process' environment variables after it has been created).

Note that with macOS and Linux installations, VS Code will try to source an environment from shell-specific user-level configuration files (Ex. ~/.bashrc and ~/.zshrc) even when not manually launched from such shells by creating such a shell and starting itself from that shell. For relevant documentaiton, see here.

See also How can I specify environment variables for the VS Code process in my VS Code settings?

For shell processes in the integrated terminal

See the terminal.integrated.env.<platform> settings, where <platform> is one of "windows", "osx", or "linux". The setting's description reads:

Object with environment variables that will be added to the VS Code process to be used by the terminal on <platform>. Set to null to delete the environment variable.

See also the related terminal.integrated.inheritEnv setting. Its description reads:

Whether new shells should inherit their environment from VS Code, which may source a login shell to ensure $PATH and other development variables are initialized. This has no effect on Windows.

For task processes

Use the task's options property's env property. Similar to the terminal.integrated.env.<platform> setting, this setting's value is a JSON object mapping environment variable names to values. The setting's description reads:

The environment of the executed program or shell. If omitted the parent process' environment is used.

For run / debug processes (launch.json)

Each launch configuration can decide how it wants to allow you to configure this. According to VS Code's documentation, "Many debuggers support some of the following attributes: [...] env - environment variables (the value null can be used to "undefine" a variable)". Other extensions that contribute launch configuration types may use a different schema, such as the cppdbg from the cpptools extension, which uses a format like [ { "name": "config", "value": "Debug" } ].

For processes related to specific extensions

This is only if those extensions contribute settings to do such configuration.

For example,

  • The CMake Tools extension contributes various settings, which are documented here, including cmake.environment, cmake.configureEnvironment, cmake.buildEnvironment, and cmake.testEnvironment.
  • The Python extension has the python.envFile setting, and launch configurations of the python type can also have a envFile property. You can find related docs here.

There's a slightly related feature-request about this here for the extension host process: API: allow an extension to change the environment variables #152806. See also this comment there about more broadly applying it to the "root" VS Code process, this update/summary, and this note about using process.env for the extension host.

starball
  • 20,030
  • 7
  • 43
  • 238
0

If you've already assigned the variables using the npm module dotenv, then they should show up in your global variables. That module is here.

While running the debugger, go to your variables tab (right click to reopen if not visible) and then open "global" and then "process." There should then be an env section...

enter image description here

enter image description here

enter image description here

Harrison Cramer
  • 3,792
  • 9
  • 33
  • 61
0

Since VS Code uses powershell in the terminal. The powershell command is

$env:NAME='VALUE'

To learn more: https://www.tutorialspoint.com/how-to-set-environment-variables-using-powershell

slacker247
  • 25
  • 4
  • 2
    1 VS code uses whatever terminal you set it up to use, though powershell is the default (mine is on bash), 2 environment variables created directly in VS code's terminal window may not persist between sessions. – Andrew Mar 17 '22 at 00:36
-1

As it does not answer your question but searching vm arguments I stumbled on this page and there seem to be no other. So if you want to pass vm arguments its like so

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "java",
      "name": "ddtBatch",
      "request": "launch",
      "mainClass": "com.something.MyApplication",
      "projectName": "MyProject",
      "args": "Hello",
      "vmArgs": "-Dspring.config.location=./application.properties"
    }
  ]
}
Alex
  • 624
  • 1
  • 9
  • 12