VSCode Custom Variables in Launch Settings? - visual-studio-code

Is there a way to add custom variables that I can use in my launch.json settings for debugging in VSCode? Currently, the only way I have found is to add them to my workspace settings and refer to the from the ${config} predefined variable.
I'd like to define variables/properties in the launch.json and use them. Here's an example of what that might look like if I wanted to add myCustomVar to all my URLs:
{
"version": "0.2.0",
"myCustomVar": "my_value",
"configurations": [
{
"name": "Page 1",
"type": "chrome",
"request": "launch",
"url": "http://localhost/page1.html?customVar=${myCustomVar}",
"sourceMaps": true,
"webRoot": "${workspaceFolder}/dev"
},
{
"name": "Page 2",
"type": "chrome",
"request": "launch",
"url": "http://localhost/page2.html?customVar=${myCustomVar}",
"sourceMaps": true,
"webRoot": "${workspaceFolder}/dev"
}
}

Input variables might work?
Command variables are already powerful but they lack a mechanism to configure the command being run for a specific use case. For example, it is not possible to pass a prompt message or a default value to a generic "user input prompt".
This limitation is solved with input variables which have the syntax: ${input:variableID}. The variableID refers to entries in the inputs section of launch.json and tasks.json, where additional configuration attributes are specified. Nesting of input variables is not supported.
The following example shows the overall structure of a tasks.json that makes use of input variables:
{
"version": "2.0.0",
"tasks": [
{
"label": "task name",
"command": "${input:variableID}"
// ...
}
],
"inputs": [
{
"id": "variableID",
"type": "type of input variable"
// type specific configuration attributes
}
]
}
Otherwise, you should be able to add custom settings to your VS Code settings.json file (it will warn you about "Unknown Configuration Setting") and insert them using ${config:myCustomVar}.

Related

set an environment variable when running test from run button in VSCODE

I am creating some tests in Flutter, but I need to set an environment variable before running the tests. Is there a way to set an environment variable when running the app from these "Run | Debug" buttons?
With the new update to the Dart SDK it is possible:
https://dartcode.org/releases/v3-11/
[...] For example, to add CodeLens for a launch config that sets a RELEASE_MODE=true environment variable to tests in test/integration_tests:
{
"name": "Current File (release mode)",
"type": "dart",
"request": "launch",
"codeLens": {
// Types of CodeLens to inject
"for": [ "run-test", "run-test-file", "debug-test", "debug-test-file" ],
// Restrict to certain folders
"path": "test/integration_tests",
// Text for CodeLens link (${debugType} will be replaced with "run" or "debug")
"title": "${debugType} (release)"
},
"env": { "RELEASE_MODE": true }
}
This will insert additional CodeLens links into tests, groups and main functions:
Using the --dart-define flag worked for me:
"configurations": [
{
"name": "Launch App",
"request": "launch",
"type": "dart",
"args": [
"--dart-define", "GOOGLE_OAUTH_CLIENT_ID=xxxxx",
"--dart-define", "GOOGLE_OAUTH_CLIENT_SECRET=yyyyy"
],
}
]
And then use it in the code as such:
String.fromEnvironment('GOOGLE_OAUTH_CLIENT_ID');
Note you may need to explicitly specify a const variable or assignment

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

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?

Is there any way to set environment variables in 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"
}
]
}

vscode: command for user input in debug launch config

I want to do something similar to whats outlined in this documentation for selecting a process, except I want to just be able to input any string:
{
"name": "Attach to Process",
"type": "node",
"request": "attach",
"processId": "${command:PickProcess}",
"port": 9229
}
Is there a command that I can use to get any user input? Ideally I could do something like this:
{
"name": "Launch Chrome Debug",
"type": "chrome",
"request": "launch",
"url": "http://localhost:8080/?id=${command:UserInput}",
"webRoot": "${workspaceRoot}",
}
That way I could specify the "id" param when I launch the debugger.
v1.30 has added this functionality: input variables during tasks and debug.
For user input variables, we introduced a new variable category input,
which results in this syntax: ${input:variableName}. This simple
syntax is not sufficient to present meaningful UI to the end user, so
we've introduced a new inputs section in launch.json and tasks.json,
where additional configuration attributes are specified.
Here is the list of supported attributes:
id - The corresponding variable name for which these attributes are
used.
type - The type of user input widget. In this release, promptString
(for a string InputBox) and pickString (for a string Quick Pick) are
supported.
description - Descriptive text shown to the user.
default - The default value to use if the user just presses Enter.
A first example shows how to use a user input variable in a task
configuration (tasks.json):
{
"tasks": [
{
"label": "Echo input",
"type": "shell",
"command": "echo ${input:echoPrompt}"
}
],
"inputs": [
{
"id": "echoPrompt",
"description": "Please enter a value",
"default": "default echo text",
"type": "promptString"
}
]
}
Another example shows a user input variable for selecting between two
options in a debug configuration (launch.json):
{
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"program": "${workspaceFolder}/${input:pickProgram}"
}
],
"inputs": [
{
"id": "pickProgram",
"description": "Select client or server",
"type": "pickString",
"options": ["client.js", "server.js"],
"default": "client.js"
}
]
}
We plan to combine user input variables with the existing
command-based variables so that user input variables can be
contributed by extensions.