跳至主要内容

向 devcontainer.json 文件添加功能

使用功能,您可以快速将工具、运行时或库添加到您的开发容器配置中。

功能是安装代码和开发容器配置的独立单元,旨在跨各种基础容器镜像工作。您可以使用功能快速将工具、运行时或库添加到您的 Codespace 镜像中。有关更多信息,请参阅开发容器网站上的可用功能功能规范

您可以从 VS Code 或 GitHub 上的仓库向devcontainer.json文件添加功能。使用本文中的选项卡显示添加功能的每种方法的说明。

devcontainer.json文件添加功能

  1. 导航到 GitHub 上的仓库,找到您的devcontainer.json文件,然后单击以编辑文件。

    如果您还没有devcontainer.json文件,您可以立即创建一个。有关更多信息,请参阅“开发容器简介”。

  2. 在文件编辑器的右侧,Marketplace 选项卡中,浏览或搜索您要添加的功能,然后单击功能名称。

    Screenshot of the "Marketplace" tab with "Terra" in the search box and the Terraform feature listed in the search results.

  3. 在“安装”下,单击代码片段将其复制到剪贴板,然后将代码片段粘贴到您的 `devcontainer.json` 文件中的 `features` 对象中。

    Screenshot of the "Marketplace" tab showing the installation code snippet for Terraform.

    "features": {
         // ...
         "ghcr.io/devcontainers/features/terraform:1": {},
         // ...
     }
    
  4. 默认情况下,将使用该功能的最新版本。要选择其他版本或配置该功能的其他选项,请展开“选项”下列出的属性以查看可用值,然后通过手动编辑 `devcontainer.json` 文件中的对象来添加选项。

    Screenshot of the "Options" section of the "Marketplace" tab, with the "version" and "tflint" properties expanded.

    "features": {
         // ...
         "ghcr.io/devcontainers/features/terraform:1": {
             "version": "1.1",
             "tflint": "latest"
         },
         // ...
     }
    
  5. 提交对 `devcontainer.json` 文件的更改。

配置更改将在从存储库创建的新 codespace 中生效。要使更改在现有 codespace 中生效,您需要将 `devcontainer.json` 文件的更新拉取到您的 codespace 中,然后重建 codespace 的容器。更多信息,请参见“Dev 容器简介”。

要在本地工作且未连接到 codespace 时在 VS Code 中添加功能,您必须安装并启用“Dev Containers”扩展。有关此扩展的更多信息,请参见VS Code Marketplace

  1. 使用 Shift+Command+P(Mac)或 Ctrl+Shift+P(Windows/Linux)访问 VS Code 命令面板。

  2. 开始键入“add dev”,然后单击Codespaces:添加 Dev Container 配置文件

    Screenshot of the Command Palette, with "add dev" entered and "Codespaces: Add Dev Container Configuration Files" listed.

  3. 单击修改您的活动配置

  4. 更新您的功能选择,然后单击确定

  5. 如果您在 codespace 中工作,则右下角会显示一个提示。要重建容器并将更改应用于您正在使用的 codespace,请单击立即重建

    Screenshot of the message: "We've noticed a change to the dev container configuration." Below this is the "Rebuild Now" button.