在 NodeJS/Express 项目中找不到已安装的模块 'express-validator'

Installed module 'express-validator' cannot be found in NodeJS/Express project

我想验证端点在调用它时收到的输入。因此,我在我的 NodeJS Web 应用程序中安装了 express-validator。但是,当我尝试使用它时,它会抛出错误:

Cannot find module 'express-validator' or its corresponding type declarations

当我导入它(即 import { validationResult } from "express-validator";)或将其设置为常量并需要它时,就会发生这种情况。在后者中,它声明找不到模块。我已经 docker 化了项目,这是我设置的 docker 文件:

FROM node:12

WORKDIR /app

COPY package*.json ./

RUN npm install

COPY . .

EXPOSE 8000

CMD ["npm", "run", "dev"]

目前,我不是 运行 生产版本,这就是为什么我是 运行 开发人员。这是我的 docker-compose 文件:

services:
  db:
    image: postgres:12
    environment:
      - POSTGRES_DB=server_side
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=123321
  app:
    build:
      context: .
      dockerfile: Dockerfile
    volumes:
      - ./src:/app/src
    ports:
      - "8000:8000"
    depends_on:
      - db
    environment:
      - POSTGRES_DB=server_side
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=123321
      - POSTGRES_HOST=db

安装模块时,它被添加到我的依赖项中:

{
  "name": "Servier-side",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "tsc",
    "dev": "concurrently \"nodemon\" \"nodemon -x tsoa spec\"",
    "start": "node build/index.js",
    "predev": "npm run swagger",
    "prebuild": "npm run swagger",
    "swagger": "tsoa spec",
    "typeorm": "node --require ts-node/register ./node_modules/typeorm/cli.js",
    "migrate:generate": "npm run typeorm migration:generate -- -n",
    "migrate:run": "npm run typeorm migration:run",
    "migrate:revert": "npm run typeorm migration:revert",
    "schema:drop": "npm run typeorm schema:drop"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/express": "^4.17.13",
    "@types/morgan": "^1.9.3",
    "@types/node": "^16.11.10",
    "@types/swagger-ui-express": "^4.1.3",
    "concurrently": "^6.4.0",
    "nodemon": "^2.0.15",
    "ts-node": "^10.4.0",
    "typescript": "^4.5.2"
  },
  "dependencies": {
    "express": "^4.17.1",
    "express-validator": "^6.13.0",
    "morgan": "^1.10.0",
    "pg": "^8.7.1",
    "reflect-metadata": "^0.1.13",
    "swagger-ui-express": "^4.1.6",
    "tsoa": "^3.2.1",
    "typeorm": "^0.2.41"
  },
  "nodemonConfig": {
    "watch": [
      "src"
    ],
    "ext": "ts",
    "exec": "ts-node src/index.ts"
  }
}

如果有人能阐明此事,我将不胜感激。为了排除可能的原因,我也尝试了Joi,但我最终遇到了同样的问题。所以,我想了解的是导致问题的原因 - 为什么它适用于其余依赖项而不是这个依赖项以及应该如何解决问题?

这种错误一般出现在需要为模块添加@types dependency

运行 docker compose with the build flag docker-compose up --build 修复了问题。