我有一个使用 Vuejs 框架构建的静态网站。该网站本身相当轻量级,我将其移至 VS Code 开发容器中,以便一些同事可以更方便地共享/重用它。
但是我注意到运行
npm install
和 npm run serve
需要更长的时间;我怀疑这与主机和容器之间的目录node_modules
同步有关。
这是预期的结果还是有优化性能的方法?
devcontainer.json
{
"name": "Personal Website Dev Container",
"dockerFile": "../Dockerfile",
"forwardPorts": [8080],
"settings": {
"terminal.integrated.shell.linux": "/bin/bash"
},
}
Dockerfile
FROM node:latest
WORKDIR /app
COPY . .
EXPOSE 8080
是的,这是意料之中的;)您可以查看以下链接以加快某些操作的速度。
基本上,如果您不使用
docker-compose
,这就是您必须执行的操作(从 Microsoft 网站复制)
请按照以下步骤操作:
- 使用
中的workspaceMount
属性告诉 VS Code 在哪里绑定源代码。然后使用 mounts 属性(VS Code 1.41+)将devcontainer.json
子文件夹挂载到指定的本地卷中。node_modules
"mounts": [ "source=${localWorkspaceFolderBasename}-node_modules,target=${containerWorkspaceFolder}/node_modules,type=volume" ]
注意: 您可以在
中使用${localWorkspaceFolderBasename}
、${devcontainerId}
或硬编码名称。source
- 由于此存储库以非根“节点”用户身份运行 VS Code,因此我们需要添加 postCreateCommand 以确保用户可以访问该文件夹。
"remoteUser": "node", "mounts": [ "source=${localWorkspaceFolderBasename}-node_modules,target=${containerWorkspaceFolder}/node_modules,type=volume" ], "postCreateCommand": "sudo chown node node_modules"
如果您将在容器中运行
,则不需要第二步。root
如果您已经构建了容器并连接到它,请从命令面板 (F1) 运行 Dev Containers: Rebuild Container 以获取更改。否则运行 Dev Containers: Open Folder in Container... 以连接到容器。
关于此方法的两个注意事项:
如果删除容器中的
文件夹,可能会丢失与卷的连接。需要时删除node_modules
文件夹的内容 (node_modules
)。rm -rf node_modules/* node_modules/.*
您会发现使用此方法在本地创建了一个空的
文件夹。这是因为容器中的卷安装点位于本地文件系统绑定安装内部。这是预期的且无害的。node_modules