前言
使用 Docker 與 VS Code 可以優化整個本地開發環境,加速項目進度過程。在所有環境中使用相同的基礎映像,為所有開發人員提供相同的編輯器工具,可以更容易實現標準。
大型項目的團隊首先必須確保安裝依賴、內核版本這些開發環境是統一的。為了解決開發環境一致性的問題,常規傳統的辦法就是制定開發人員遵循制定指南,但是盡管如此實際開發過程還是會遇到各種障礙。
設置環境的常規方法如下圖所示:

另一種解決方案是使用所有必需的庫和依賴項預先配置的開發環境,開發人員可以在容器中分拆這些庫和依賴項。然后,開發人員可以在容器提供的隔離環境中工作。這極大地減少了開發人員在克隆代碼庫以開始處理它之間花費的時間。

除了為所有開發人員提供相同的環境之外,我們可以利用它來自動安裝您的項目所需的特定擴展。這可以避免工具的不一致使用,并且省去開發人員手動安裝的麻煩。
以下是通過結合使用 Docker 和 VS Code 的Remote — Containers擴展來實現的。
設置
在本文中,我將提供一個在 Node 環境中運行的 JavaScript 應用程序示例。閱讀在容器內開發以獲取所有技術堆棧的詳細文檔。
如果您尚未安裝Docker和 VS Code,請先安裝它們。在 VS Code 中安裝Remote — Containers擴展。確保 Docker 正在您的機器上運行。
轉到您的項目并在根目錄中創建一個名為.devcontainer的文件夾。這個新文件夾包含開發容器所需的配置文件。
在.devcontainer 中創建Dockerfile和devcontainer.json并添加以下配置。
Dockerfile文件如下
# Specify the base image you want your dev container to use.
# You may use the same exact base image your application would use in production for consistancy.
# That could prevent surprises such as "works in local, but not in PROD".
FROM node:14.17.0-alpine
# Additionally you can install other dependencies for the environment while configuring the base image.
# In this example, I am installing Git as the Alpine version of node does not come with one.
RUN apk update
RUN apk add git
devcontainer.json文件如下
{
"name": "DevContainer ReactApp",
// Provide the dev container with a Dockerfile that it can use to build an image and run the container.
"dockerFile": "Dockerfile",
// Command(s) to run before the container is created.
// In this case we are installing the node modules.
"initializeCommand": "yarn install",
// Starts the development server every time the container starts.
// This is triggered on reopening the container as well.
"postStartCommand": "yarn start",
// Forward your application's port(s) running in the container to the local machine.
"forwardPorts": [3000],
// Required VSC code extensions that you want to automatically install for the developers to use.
"extensions": [
"dbaeumer.vscode-eslint",
"esbenp.prettier-vscode",
"eamodio.gitlens"
]
// Use the devcontainer.json reference to explore all possible configurations.
// https://code.visualstudio.com/docs/remote/devcontainerjson-reference
}
完成后,我們需要構建容器。為此,請使用 VS Code 命令面板中的“在容器中打開文件夾”或“在容器中重新打開”。


這應該初始化開發容器。它拉取 docker 基礎鏡像,配置容器,并啟動開發服務器。


結語
容器的構建和配置是一次性活動,需要時間。如果沒有更改,后續重建會更快。但是,如果 devcontainer.json 或 Dockerfile 發生更改,則需要重新構建以應用更改。如果您嘗試直接重新打開,系統將提示您重建。
到此這篇關于使用Vscode結合docker進行開發的的文章就介紹到這了,更多相關Vscode結合docker開發內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持腳本之家!