打字稿:在Docker容器中找不到模块XWZ或其对应的类型声明

时间:2020-09-02 01:19:58

标签: node.js typescript docker typescript-typings

环境:运行nodejs映像的Docker容器。

api正常工作。 ts-node-dev运行完美,Express或其他软件包没有问题。 数据库也正在工作,我已经通过工作台对其进行了测试。

尝试使用ORM连接到数据库时出现错误。我尝试了其中两个:TypeORM和Sequelize。两者都引发了相同类型的错误:

error TS2307: Cannot find module 'sequelize' or its corresponding type declarations.

我不知道Typescript编译器或docker环境是否有问题。因为只有在我通过docker-compose up在容器内运行应用程序时,这种情况才会发生。

我注意到的是,这两个库都使用库内类型声明,我的意思是,没有@ types / sequelize

这是重现该错误的资源库: https://bitbucket.org/carloseustaquio/test-cicd-docker/src/master/

Dockerfile

FROM node:12

RUN mkdir -p /home/node/api/node_modules && chown -R node:node /home

WORKDIR /home/node/api

COPY package.json yarn.* ./

USER node

RUN yarn

COPY --chown=node:node . .

EXPOSE 8080

ENTRYPOINT [ "./init.sh" ]

docker-compose.yaml

version: '3'

services:
  nodejs-app:
    container_name: nodejs-app
    build: '.'
    volumes:
      - .:/home/node/api
      - /home/node/api/node_modules
    networks:
      - app-connect
    ports:
      - '8080:8080'
    depends_on: 
      - database
    environment: 
      - DB_URI=mysql://root:password@database/db?charset=UTF8

  database:
    image: mysql:5.7
    environment: 
      - MYSQL_ROOT_PASSWORD=password
      - MYSQL_DATABASE=db
    ports: 
      - 0.0.0.0:7200:3306

networks:
  app-connect:
      driver: bridge

package.json

{
  "name": "test-docker",
  "version": "1.0.0",
  "description": "testing docker envairoment",
  "main": "index.js",
  "scripts": {
    "dev": "ts-node-dev --respawn --ignore-watch node_modules --no-notify index.ts",
    "build": "tsc",
    "start": "node dist/index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "mysql2": "^2.1.0",
    "sequelize": "^6.3.5"
  },
  "devDependencies": {
    "@types/express": "^4.17.8",
    "@types/node": "12",
    "@types/validator": "^13.1.0",
    "ts-node-dev": "^1.0.0-pre.61",
    "typescript": "^4.0.2"
  }
}

tsconfig.json

{
  "compilerOptions": {
    "target": "es2017",
    "module": "commonjs",
    "moduleResolution": "node",
    "lib": [
      "es6"
    ],
    "typeRoots": [
      "./node_modules/@types",
      "./src/@types",
    ],
    "allowJs": true,
    "outDir": "./dist",
    "rootDir": ".",
    "strict": true,
    "esModuleInterop": true,
    "noImplicitAny": false,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
  }
}

1 个答案:

答案 0 :(得分:0)

尝试npm i @types/sequelize获取模块的类型或使用dts-gen生成声明。