如何在 VS Code 的 tasks.json 文件中访问 .env 变量?

8

我正在尝试在vscode的C#项目的tasks.json文件中,在任务中使用环境变量。

在我的launch.json文件中,我有以下代码来解析一个.env文件:

"configurations": [
  {
    ...
    "envFile": "${workspaceFolder}/.env",
  }
]

然后我在tasks.json文件中有这个任务:

{
  "label": "login",
  "command": "sh",
  "type": "shell",
  "args": [
    "${workspaceFolder}/etc/login.sh",
    "${env:USERNAME}",
    "${env:PASSWORD}"
  ]
}

这似乎是从https://code.visualstudio.com/docs/editor/tasks中暗示的代码,但是(通过在另一个任务中回显测试)我发现这最后两个args为空白。在网上调查后,我认为我已经找到了原因,configurations..env被任务本身使用,而不是被运行的task.json访问,因此无法访问。

我如何在tasks.json中创建(使用)这些env变量


请看这里 https://dev59.com/aVMI5IYBdhLWcg3wZKdQ#70748562。 - Eduardo Lucio
2个回答

3

请查看https://code.visualstudio.com/docs/editor/tasks-appendix了解更多关于任务的信息。

  /**
   * The environment of the executed program or shell. If omitted
   * the parent process' environment is used.
   */
  env?: { [key: string]: string };

范例

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label": "diagnostic",
            "type": "shell",
            "options": {
                "cwd": "${workspaceFolder}/beam",
                "env": {
                    "FOO": "baz",
                }
            },
            "command": "printenv",
            "problemMatcher": []
        }
    ]
}

我不知道有没有办法像launch.json那样从文件中提取这些信息。

我建议在vscode仓库上开一个问题(issue)。


1

我有同样的问题。 我使用的是Windows系统。 我已经解决了这个问题。 对我来说,问题出在VSCode中的设置:

"terminal.integrated.automationShell.windows": "C:/Program Files/Git/bin/bash.exe"

这导致环境无法正确加载。
我能够访问从Windows GUI环境变量工具中设置的Windows设置,但无法访问在我的.bashrc中设置的环境变量。 我注释掉了那个设置。

我还将终端>集成>默认配置文件:Windows 设置为Git Bash。

通过这些更改,我能够访问我的.bashrc文件中的环境变量。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接