You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VSCode Dev Container无法导入npm包问题求助

VSCode Dev Container前端项目导入/node_modules模块失败问题

我在调试VSCode Dev Container中的导入解析问题上耗费了大量时间。启动前端Dev Container后,从/node_modules导入模块时会返回错误:"Cannot find module"。

错误截图

已确认Docker容器内确实安装了相关依赖包,但只有在本地安装包时问题才能解决——这和Dev Container环境隔离的核心定位相矛盾。我的Python Dev Container可以正常识别Docker解释器并导入pip包,没有出现类似问题。

以下是项目相关的配置文件:

docker-compose.yml

frontend:
    build:
      context: ./frontend
      dockerfile: Dockerfile
    volumes:
      - .:/workspace:cached # Mount the root folder that contains .git
    ports:
      - '3000:3000'
    environment:
      - NODE_ENV=development

Dockerfile

# Use the official Node.js 18 image, Alpine version.
FROM node:20-alpine

# Install Git and OpenSSH
RUN apk add --no-cache git openssh

# Create and change to the app directory.
WORKDIR /frontend

# Copy package.json and package-lock.json, and install dependencies.
COPY package*.json ./

RUN npm install --frozen-lockfile

# Copy the rest of the files
COPY . .

# Expose the port the app runs on.
EXPOSE 3000

# Start the development server using the `dev` script from your package.json.
CMD ["npm", "run", "dev"]

.devcontainer配置文件

{ 
  "name": "Frontend Development",
    "dockerComposeFile": ["../../docker-compose.yml"],
    "service": "frontend",
  "workspaceFolder": "/workspace/frontend",
    "shutdownAction": "none",
  "customizations": {
    "vscode": {
      "settings": {
        "editor.defaultFormatter": "esbenp.prettier-vscode",
        "editor.formatOnSave": true,
        "terminal.integrated.inheritEnv": true

      },
      "extensions": [
        "dbaeumer.vscode-eslint",
        "esbenp.prettier-vscode",
        "ms-azuretools.vscode-docker"
      ]
    }
  },
  "mounts": [
    "type=bind,source=${localWorkspaceFolder},target=/workspace",
    "type=bind,source=/Users/${localEnv:USER}/.ssh,target=/root/.ssh,readonly"
  ]
}

我也曾尝试为node_modules创建卷以避免与本地文件冲突,但问题仍未解决。目前所有尝试均无效,恳请帮助。

内容的提问来源于stack exchange,提问作者Ethan Cavill

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 04:06:18