Is there any way to set environment variables in Visual Studio Code? - visual-studio-code

Could you please help me, how to setup environment variables in visual studio code?

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}"
}
]
}

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"
},
...
}
]
}

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

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.

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.

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.

For C/C++ debugging this works for me (docs):
// Defined per configuration in launch.json
"environment": [
{
"name": "<env_name>",
"value": "<env_value>"
}
]

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

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...

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"
}
]
}

Related

How to restart/reload VS Code host window on extension source code file changes?

I'm developing a VS Code extension following the vscode-extension-samples/helloworld-sample.
Question:
Is there a way to Hot Module Replace or otherwise "patch" the source code loaded by the host window?
Alternatively is there a way to reload the host window on source code changes?
When running the Run Extension launch configuration, tsc is executed in --watch mode watching for file changes and a new VS Code window is launched acting as the in-development-extension's host.
Expectation:
Updating the extentions's source code (e.g. extension.ts) updates the hosted extension's behaviour accordingly.
Actual:
Updating the extentions's source code dosn't have any effect in the hosted extension's behaviour.
Notes:
Updating the extentions's source code and then manually hitting Ctrl + R to reload the extension host window seems to "reload" the latest version of the extension's source code too, updating the hosted extension's behaviour as expected.
Here's my current config source code:
// launch.json
{
"version": "0.2.0",
"configurations": [{
"name": "Develop Extension",
"type": "extensionHost",
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": ["--extensionDevelopmentPath=${workspaceFolder}"],
"outFiles": ["${workspaceFolder}/dist/**/*.js"],
"preLaunchTask": "npm: dev",
"postDebugTask": "Terminate All Tasks",
},
]
}
// tasks.json
{
"version": "2.0.0",
"tasks": [
{
"type": "npm",
"script": "dev",
"detail": "Launch extension for local development in a new (host) VS Code window.",
"problemMatcher": "$tsc-watch",
"isBackground": true,
"presentation": { "reveal": "always" },
"group": {
"kind": "build",
"isDefault": true,
},
"icon": { "id": "tools" },
},
{
"label": "Terminate All Tasks",
"detail": "Stop all running tasks.", // e.g. useful for endless tasks like file watchers
"command": "echo ${input:terminate}",
"type": "shell",
"problemMatcher": [],
"icon": { "id": "stop-circle" },
},
],
"inputs": [
{
"id": "terminate",
"type": "command",
"command": "workbench.action.tasks.terminate",
"args": "terminateAll",
},
],
}
There's no automatic reload of the extension development host. You have to do it manually.

How do I make vs code put the output of my c program in TERMINAL panel?

I'm trying to build and run C code with vscode on windows 10.
I've gone through the vscode doc for mingw configuration, followed the steps there and managed to run a .c file with vscode.
However, there's still an issue yet.
each time run my program via "Run | Run Without Debugging", the panel switches automatically to "TERMINAL"
So I have to switch to the DEBUG CONSOLE manually each time I run the code, which is tediously boring.
Is there a way to keep the "DEBUG CONSOLE" panel active or show the output of my program in "TERMINAL" panel
I also tried the suggestion in another stackoverflow post, but it doesn't work for me.
tasks.json
Here is my tasks.json
{
"version": "2.0.0",
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: gcc.exe build active file",
"command": "E:\\MinGW\\bin\\gcc.exe",
"args": [
"-g",
"${file}",
"-o",
"${fileDirname}\\${fileBasenameNoExtension}.exe"
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "compiler: E:\\MinGW\\bin\\gcc.exe"
}
]
}
launch.json
Here is my launch.json
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "gcc.exe - Build and debug active file",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}\\${fileBasenameNoExtension}.exe",
"args": [],
"stopAtEntry": false,
"cwd": "${fileDirname}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"miDebuggerPath": "E:\\MinGW\\bin\\gdb.exe",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "C/C++: gcc.exe build active file"
}
]
}
How do I make vs code put the output of my c program in TERMINAL panel?
You can use Code Runner with some simple configuration.
Install Code Runner.
Type Ctrl + Shift + P
Search and open Open Settings(JSON)
Add the following json snippets to your settings.json:
"code-runner.runInTerminal": true
Every time you want to run your c code, just type the icon from the upper right corner that Code Runner provide.
For step 4, you can also open vscode settings and change it on GUI.

Variables in VS Code settings, how?

In VS Code settings, there are some fields which I configure the same. These would be namely font and font size. Generally I have them all set to the same. I am trying to set up a variable in the settings.json which can be applied to all of them. After reading through Variables Reference for VS Code, I came up with the following:
{
"common": [
{
"font": "Anonymous Pro",
"fontSize": 10,
}
],
// Set up the Editor
"editor.fontFamily": "${common:font}",
"editor.fontSize": "${common:fontSize}",
"terminal.integrated.fontFamily": "${common:font}",
"terminal.integrated.fontSize": "${common:fontSize}",
"debug.console.fontFamily": "${common:font}",
"debug.console.fontSize": "${common:fontSize}",
}
Though, this doesn't seem to work. Is there a way to setup variables within the settings.json without having to setup environment variables?
Thanks!
Currently you cannot set variables in the settings.json file.
The current open issue for VS Code to implement this feature is here: https://github.com/microsoft/vscode/issues/2809
It has yet to have a PR and the opening of the issue occurred Feb 2016, but with comments within the last 2 months.
For anyone coming to this question in 2023, VS Code has updated a way to provide this using the c_cpp_properties.json configuration.
Here is an example of variable definition:
{
"configurations": [
{
"customConfigurationVariables": {
"appInstallPath": "/my/app/bin/",
"debugRemoteHost": "192.168.1.1",
"debugRemotePort": "2159"
}
}
],
"version": 4
}
And then you would reference these variables in either launch.json or tasks.json using
${input:variable-id}
where the variable-id is defined in the input section as shown below. The "args" key must match your variable defined in customConfigurationVariables:
{
"version": "0.2.0",
"inputs": [
{
"id": "installPath",
"type": "command",
"command": "cpptools.activeConfigCustomVariable",
"args": "appInstallPath"
},
{
"id": "host",
"type": "command",
"command": "cpptools.activeConfigCustomVariable",
"args": "debugRemoteHost"
},
{
"id": "port",
"type": "command",
"command": "cpptools.activeConfigCustomVariable",
"args": "debugRemotePort"
}
],
"configurations": [
{
// Enables single-click remote debugging on this device from the project install location
"name": "Local Debug",
"type": "cppdbg",
"request": "launch",
"program": "${command:cmake.launchTargetPath}",
"cwd": "${input:installPath}",
"environment": [],
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
},
{
"description": "Set Disassembly Flavor to Intel",
"text": "-gdb-set disassembly-flavor intel",
"ignoreFailures": true
}
],
"stopAtEntry": true,
"externalConsole": false,
"logging": {
"engineLogging": false,
"trace": false,
"traceResponse": false
}
}
]
}
This is not possible. The link you provided states:
Variable substitution is supported inside key and value strings in launch.json and tasks.json ...
So there is no support for settings.json.
What are you trying to achieve? You can set project specific settings in VSCode. So much you can have a different set of fonts and settings based on the project. But I don't think the settings.json supports variables.
VScode: Defining own variables in tasks.json
Check out this Might help I have developed a python script that reads any *.json file and replace content with $[] with its actual value

Debugging using Visual Studio Code and piping terminal output to a file

I am using VS Code to debug an application on Ubuntu, using a launch.json file and cmake to build and debug. This works fine and I can see the output of the program in the terminal as expected. However, I would like to automatically save this output to a file. The way I would do this typically would be something like mycommand > terminal_output.txt, however I can't find a way of replicating this using the launch.json file, or alternatively of running the debug through the terminal (e.g. something along the lines of debug --flags launch.json > terminal_output.txt).
Here is my launch.json for reference:
{
"version": "0.2.0",
"configurations": [
{
"name": "g++-8 build and debug active file",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}/${fileBasenameNoExtension}",
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "g++-8 build active file",
"miDebuggerPath": "/usr/bin/gdb"
}
]
}
Is there a way of doing this in a simple way?
Since I am using cmake, I was able to achieve this using cmake.debugConfig in my settings.json file:
{
"cmake.debugConfig": {
"args": [
">",
"test.txt"
]
}
}
Adding "args" in launch.json, however, did not work.
install CodeLLDB extension
launch.log: inside a CodeLLDB launch configuration add
"stdio": [null, null, "debug.log"] // stdin/stdout/stderr
stdio redirection for CodeLLDB

VSCode - environment variable set in settings.json is undefined in Node debug terminal

I set an environment variable as such in settings.json:
{
"terminal.integrated.env.linux": {
"GOOGLE_APPLICATION_CREDENTIALS": "${env:HOME}/xyz.json"
},
"terminal.integrated.shellArgs.linux": ["-l"]
}
I can confirm that it is set correctly in the integrated terminal.
When I debug in Node, the same variable appears as undefined. Is this expected behavior?
I can get around this by also defining it in launch.json as such:
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"program": "${workspaceFolder}/server.js",
"env": { "GOOGLE_APPLICATION_CREDENTIALS": "${env:HOME}/xyz.json" }
}
]
}
But what I would ideally like is to define it in only one place and be done with it.
Yes, I could also define it in .profile and have it passed to VSCode through the "terminal.integrated.shellArgs.linux": ["-l"] option in settings.json but there are other reasons I don't want to do this.
Thoughts?