I am setting up a NodeJS + Mysql + Typescript + Docker app, but have a problem when I try to include the mysql2 npm package in my main script. In fact, whenever I include the script I get this error: Error TS2307: Cannot find module 'mysql2' or its corresponding type declarations..
Here are my files:
// src/index.ts
import 'dotenv/config';
import express, { Application, Request, Response } from 'express';
import mysql from 'mysql2';
const app: Application = express();
const pool = mysql.createPool({
host: process.env.MYSQL_HOST,
user: process.env.MYSQL_USER,
password: process.env.MYSQL_ROOT_PASSWORD,
database: process.env.MYSQL_DATABASE,
});
const db = pool.promise();
// App
app.use(express.json());
app.get('/', async (_req: Request, res: Response) => {
const results = await db.query('SELECT * FROM my_table');
[...]
});
app.listen(process.env.NODE_LOCAL_PORT, () => {
[...]
});
// package.json
{
"name": "my_app",
"version": "0.0.1",
"scripts": {
"start": "nodemon"
},
"dependencies": {
"dotenv": "^10.0.0",
"express": "^4.17.1",
"mysql2": "^2.3.0",
"nodemon": "^2.0.12",
"typescript": "^4.3.5"
},
"devDependencies": {
"@types/express": "^4.17.13",
"@types/node": "^16.4.13",
"ts-node": "^10.2.0"
}
}
// Dockerfile
FROM node:latest
WORKDIR /app/
COPY package.json yarn.lock ./
RUN yarn
COPY . /
// docker-compose.yaml
version: "3.8"
services:
web:
build:
context: .
env_file: ./.env
command: yarn start
volumes:
- .:/app/
- /app/node_modules
ports:
- $NODE_LOCAL_PORT:$NODE_DOCKER_PORT
depends_on:
- mysql
environment:
MYSQL_HOST: mysql
mysql:
image: mysql
env_file: ./.env
environment:
MYSQL_ROOT_PASSWORD: $MYSQL_ROOT_PASSWORD
MYSQL_DATABASE: $MYSQL_DATABASE
ports:
- $MYSQL_LOCAL_PORT:$MYSQL_DOCKER_PORT
volumes:
- mysql:/var/lib/mysql
- mysql_config:/etc/mysql
volumes:
mysql:
mysql_config:
Any idea of why I keep having this issue?