# 为 GitHub Codespaces 设置 Node.js 项目

通过创建自定义开发容器配置，开始在 GitHub Codespaces 中使用 Node.js、JavaScript 或 TypeScript 项目。

## 简介

本指南介绍如何设置示例 Node.js 项目 在 GitHub Codespaces 中使用 Visual Studio Code web 客户端。 这样会向你演示在 codespace 中打开项目，以及添加和修改预定义开发容器配置的过程。

完成本教程后，你将能够使用 VS Code Web 客户端或 VS Code 桌面应用程序将开发容器配置添加到自己的存储库。

有关开发容器的详细信息，请参阅“[开发容器简介](/zh/codespaces/setting-up-your-project-for-codespaces/adding-a-dev-container-configuration/introduction-to-dev-containers)”。

## 步骤 1：在 codespace 中打开项目

1. 登录到 GitHub.com（如果尚未登录）。
2. 转到 <https://github.com/microsoft/vscode-remote-try-node。>
3. 单击“使用此模板”，然后单击“在 codespace 中打开”。

   ![屏幕截图显示“使用此模板”按钮和展开的下拉菜单，其中显示了“在 codespace 中打开”选项。](/assets/images/help/repository/use-this-template-button.png)

创建 codespace 时，你的项目是在你专用的远程虚拟机上创建的。 默认情况下，codespace 的容器有许多语言和运行时，包括 Node.js、JavaScript 和 TypeScript。 它还包括一组常用工具，例如 nvm、npm、yarn、git、wget、rsync、openssh 和 nano。

可以通过调整 vCPU 和 RAM 的数量、添加点文件来个性化环境或通过修改已安装的工具和脚本来自定义 codespace。 有关详细信息，请参阅“[自定义代码空间](/zh/codespaces/customizing-your-codespace)”。

GitHub Codespaces 使用名为 `devcontainer.json` 的文件来配置在 codespace 中使用的开发容器。 每个存储库可以包含一个或多个 `devcontainer.json` 文件，以便准确提供在 codespace 中处理代码所需的开发环境。

启动时，GitHub Codespaces 使用 `devcontainer.json` 文件以及构成开发容器配置的任何依赖文件来安装工具和运行时，以及执行项目所需的其他安装任务。 有关详细信息，请参阅“[开发容器简介](/zh/codespaces/setting-up-your-project-for-codespaces/adding-a-dev-container-configuration/introduction-to-dev-containers)”。

## 步骤 2：添加开发容器配置

使用 GitHub Codespaces 的默认开发容器，可以成功地处理 [vscode-remote-try-node](https://github.com/microsoft/vscode-remote-try-node) 等 Node.js 项目。 但是，我们建议配置自己的开发容器，以包含项目所需的所有工具和脚本。 这将确保存储库中的所有 GitHub Codespaces 用户都拥有完全可复制的环境。

若要将存储库设置为使用自定义开发容器，需要创建一个或多个 `devcontainer.json` 文件。 可以在 Visual Studio Code 中从预定义配置模板中添加这些文件，也可以自行编写。 有关开发容器配置的详细信息，请参阅“[开发容器简介](/zh/codespaces/setting-up-your-project-for-codespaces/adding-a-dev-container-configuration/introduction-to-dev-containers)”。

1. 访问 Visual Studio Code Command Palette (<kbd>Shift</kbd>+<kbd>Command</kbd>+<kbd>P</kbd> / <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>P</kbd>)，然后开始键入“add dev”。 单击“Codespaces: 添加开发容器配置文件”。

   ![命令面板的屏幕截图，其中输入了“add dev”，并列出了“Codespaces: 添加开发容器配置文件”。](/assets/images/help/codespaces/add-prebuilt-container-command.png)

2. 单击“创建新配置”。

3. 在此示例中，创建 codespace 的模板存储库已包含开发容器配置，因此会显示一条消息，告知配置文件已存在。 我们将覆盖现有配置文件，因此请单击“继续”。

4. 单击“显示所有定义”。

   ![“添加开发容器配置文件”下拉菜单的屏幕截图，显示了各种选项，包括“显示所有定义”。](/assets/images/help/codespaces/show-all-definitions.png)

5. 键入 `node` 并单击“Node.js & JavaScript”。 如果项目使用特定工具，则可使用其他选项。 例如 Node 和 MongoDB。

   ![“添加开发容器配置文件”下拉列表的屏幕截图，其中显示了“Node.js 和 JavaScript”选项。](/assets/images/help/codespaces/add-node-devcontainer-config.png)

6. 选择要用于项目的 Node.js 版本。 在本例中，选择标记为“(默认)”的版本。

   ![“添加开发容器配置文件”下拉列表的屏幕截图，其中显示了各种 Node 版本，包括“18 (默认)”。](/assets/images/help/codespaces/add-node-version.png)

7. 将显示附加功能列表。 我们将安装 JSHint，这是一种用于检测 JavaScript 代码中错误的代码质量工具。 要安装此工具，请键入 `js`，选择 `JSHint (via npm)`，然后单击“确定”。

   ![“添加开发容器配置文件”下拉列表的屏幕截图，其中显示了文本框中的“js”和下拉列表中的“JSHint (via npm)”。](/assets/images/help/codespaces/add-jshint-config.png)

8. 一条消息会显示，告知开发容器配置文件已存在。 单击“覆盖”。

   创建 `devcontainer.json` 文件并在编辑器中打开。

### 自定义开发容器配置的详细信息

如果在 Visual Studio Code 资源管理器中查看，将看到一个 `.devcontainer` 目录已添加到包含 `devcontainer.json` 文件的项目存储库的根目录中。 这是从此存储库创建的 codespace 的主配置文件。

#### devcontainer.json

已添加的 `devcontainer.json` 文件将包含 `name`、`image` 和 `features` 属性的值。 包含一些可能有用的其他属性，但已注释掉。

文件类似于下面所示，具体取决于你选择的映像：

```jsonc
// For format details, see https://aka.ms/devcontainer.json. For config options, see the
// README at: https://github.com/devcontainers/templates/tree/main/src/javascript-node
{
  "name": "Node.js",
  // Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile
  "image": "mcr.microsoft.com/devcontainers/javascript-node:0-18-bullseye",
  "features": {
    "ghcr.io/devcontainers-contrib/features/jshint:2": {}
  }

  // Features to add to the dev container. More info: https://containers.dev/features.
  // "features": {},

  // Use 'forwardPorts' to make a list of ports inside the container available locally.
  // "forwardPorts": [],

  // Use 'postCreateCommand' to run commands after the container is created.
  // "postCreateCommand": "yarn install",

  // Configure tool-specific properties.
  // "customizations": {},

  // Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root.
  // "remoteUser": "root"
}
```

* **名称：** 你可以将开发容器命名为任意名称。 提供了默认值。
* **图像：** 容器注册表（[DockerHub](https://hub.docker.com/)[GitHubContainer registry](/zh/packages/learn-github-packages/introduction-to-github-packages) 或 [Azure 容器注册表](https://azure.microsoft.com/services/container-registry/)）中用于为代码空间创建开发容器的映像的名称。
* 功能：一个或多个对象的列表，其中每个对象引用一个可用的开发容器功能。 功能是安装代码和开发容器配置的独立、可共享单元。 它们提供了一种简单的方法，可将更多工具、运行时或库功能添加到开发容器。 您可以在 VS Code 中或在 `devcontainer.json` 上的 GitHub 编辑器中添加功能。 有关更多信息，请单击 Visual Studio Code 中的 \*\*\*\*\*\*\*\* 或 [Web browser](/zh/codespaces/setting-up-your-project-for-codespaces/configuring-dev-containers/adding-features-to-a-devcontainer-file?tool=webui) 选项卡。
* **forwardPorts:** 此处列出的所有端口都会自动转发。 有关详细信息，请参阅“[代码空间中的转发端口](/zh/codespaces/developing-in-a-codespace/forwarding-ports-in-your-codespace)”。
* postCreateCommand：使用此属性在创建 codespace 后运行命令。 这可以格式化为字符串（如上所示）、数组或对象。 有关详细信息，请参阅开发容器网站上的[开发容器规范](https://containers.dev/implementors/json_reference/#lifecycle-scripts)。
* 自定义：此属性允许你在 codespace 中使用特定工具或服务时自定义它。 例如，可以为 VS Code 配置特定设置和扩展。 有关详细信息，请参阅开发容器网站上的“[支持工具和服务](https://containers.dev/supporting)”。
* remoteUser：默认情况下以 vscode 用户身份运行，但可以选择将其设置为 root。
  有关可用属性的完整列表，请参阅开发容器网站上的[开发容器规范](https://containers.dev/implementors/json_reference/)。

#### 其他开发容器配置文件

如果你熟悉 Docker，除 `devcontainer.json` 文件外，你还可能需要使用 Dockerfile 或 Docker Compose 来配置 codespace 环境。 可以通过在 `devcontainer.json` 文件旁边添加 `Dockerfile` 或 `compose.yaml` 文件来实现这一点。 有关详细信息，请参阅开发容器网站上的“[使用映像、Dockerfile 和 Docker Compose](https://containers.dev/guide/dockerfile)”。

## 步骤 3：修改 devcontainer.json 文件

添加了开发容器配置并基本了解所有功能之后，现在可以进行更改以进一步自定义你的环境。 在此示例中，你将添加执行以下操作的属性：

* 创建开发容器后运行 `npm install`，以安装 `package.json` 文件中列出的依赖项。
* 在此 codespace 中自动安装 VS Code 扩展。

1. 在 `devcontainer.json` 文件的 `features` 属性后添加逗号，删除关于功能的两个取消注释行。

   ```json copy
     "features": {
       "ghcr.io/devcontainers-contrib/features/jshint:2": {}
     },

     // Features to add to the dev container. More info: https://containers.dev/features.
     // "features": {},
   ```

2. 取消注释 `postCreateCommand` 属性，并为其分配命令 `npm install`。

   ```jsonc copy
    // Use 'postCreateCommand' to run commands after the container is created.
    "postCreateCommand": "npm install",
   ```

3. 取消注释 `customizations` 属性并按如下所示对其进行编辑，以安装“代码拼写检查器”VS Code 扩展。

   ```jsonc copy
   // Configure tool-specific properties.
   "customizations": {
     // Configure properties specific to VS Code.
     "vscode": {
       // Add the IDs of extensions you want installed when the container is created.
       "extensions": [
         "streetsidesoftware.code-spell-checker"
       ]
     }
   }
   ```

   文件 `devcontainer.json` 现在应如下所示，具体取决于你选择的图像：

   ```jsonc
   // README at: https://github.com/devcontainers/templates/tree/main/src/javascript-node
   {
     "name": "Node.js",
     // Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile
     "image": "mcr.microsoft.com/devcontainers/javascript-node:0-18-bullseye",
     "features": {
       "ghcr.io/devcontainers-contrib/features/jshint:2": {}
     },

     // Use 'forwardPorts' to make a list of ports inside the container available locally.
     // "forwardPorts": [],

     // Use 'postCreateCommand' to run commands after the container is created.
     "postCreateCommand": "npm install",

     // Configure tool-specific properties.
     "customizations": {
       // Configure properties specific to VS Code.
       "vscode": {
         // Add the IDs of extensions you want installed when the container is created.
         "extensions": [
           "streetsidesoftware.code-spell-checker"
         ]
       }
     }

     // Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root.
     // "remoteUser": "root"
   }
   ```

4. 保存所做更改。

5. 访问 VS Code Command Palette (<kbd>Shift</kbd>+<kbd>Command</kbd>+<kbd>P</kbd> / <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>P</kbd>)，然后开始键入“rebuild”。 单击“Codespace: 重生成容器”。

   ![命令面板的屏幕截图，其中包含“重新生成容器”搜索，下拉列表中突出显示了“Codespace: 重新生成容器”选项。](/assets/images/help/codespaces/codespaces-rebuild.png)

   > \[!TIP]
   > 你可能偶尔需要执行一次完整重建，以清除缓存并使用全新的镜像重新构建容器。 有关详细信息，请参阅“[在 codespace 中重新生成容器](/zh/codespaces/developing-in-a-codespace/rebuilding-the-container-in-a-codespace#rebuilding-a-container)”。
   > 在代码空间内进行重建可确保在将更改提交到仓库之前，更改能够按预期工作。 如果某些问题导致了故障，您将进入带有恢复容器的代码空间中，您可以从该容器进行重建以继续调整容器。

   重新构建开发容器后，当代码空间再次可用时，将会运行`postCreateCommand`，安装 npm，并且“代码拼写检查器”扩展将可供使用。

## 步骤 4：运行应用程序

在上一部分中，你使用 `postCreateCommand` 通过 `npm install` 命令安装了一组包。 现已安装依赖项，可以运行应用程序。

1. 在 codespace 的终端中输入 `npm start`。

   ![在终端中运行“npm start”的屏幕截图。 最终输出为“在 http://0.0.0.0:3000 上运行”。](/assets/images/help/codespaces/codespaces-npmstart.png)

2. 项目启动时，VS Code 的右下角应会显示一条“toast”通知消息，提示你的应用程序可在转发的端口上可用。 要查看正在运行的应用程序，请单击“在浏览器中打开”。

   ![端口转发消息的屏幕截图，显示“端口 3000 上运行的应用程序可用”。 还显示“在浏览器中打开”按钮。](/assets/images/help/codespaces/codespaces-port3000-toast.png)

## 步骤 5：提交更改

在对 codespace 进行更改（无论是添加新代码还是更改配置）时，需要提交更改。 将配置更改提交到存储库可确保任何其他从此存储库创建 Codespace 的人都获得相同的配置。 你所做的任何自定义（如添加 VS Code 扩展）都将可供所有用户使用。

在本教程中，你从模板存储库创建了 codespace，因此 codespace 中的代码尚未存储在存储库中。 可以通过将 Current Branch 发布到 GitHub 来创建存储库。

如需相关信息，请参阅 [在代码空间中使用源控制](/zh/codespaces/developing-in-a-codespace/using-source-control-in-your-codespace?tool=webui#publishing-a-codespace-created-from-a-template)。

## 后续步骤

现应能将自定义开发容器配置添加到自己的 Node.js、JavaScript 或 TypeScript 项目中。

以下是用于更高级场景的一些额外资源。

* [向 devcontainer.json 文件添加功能](/zh/codespaces/setting-up-your-project-for-codespaces/configuring-dev-containers/adding-features-to-a-devcontainer-file?tool=webui)
* [管理 GitHub Codespaces 的账户专属的机密](/zh/codespaces/managing-your-codespaces/managing-your-account-specific-secrets-for-github-codespaces)
* [管理 GitHub Codespaces 的 GPG 验证](/zh/codespaces/managing-your-codespaces/managing-gpg-verification-for-github-codespaces)
* [代码空间中的转发端口](/zh/codespaces/developing-in-a-codespace/forwarding-ports-in-your-codespace)