'Cannot find module' when import in TypeScript

Viewed 5539

I have a small problem with importing nodejs modules. For http module this syntax is working well:

import * as http from "http";

But when I try to do the same with 'mysql2' node.js module:

import * as database from "mysql2";

I gave me an error:

Cannot find module 'mysql2'

And refuse to compile that line. I even tried syntax like this (don't know why):

import {database} from 'mysql2';

But there's no error only when I write like this:

let database = require('mysql2');

In tsconfig.json I've set:

"module": "commonjs",
"moduleResolution": "node",

And of course I've already installed the modules through npm in project folder:

npm install mysql2 --save

So my question is, why the import don't work and I have error in Visual Studio Code?

2 Answers

Install the typescript type definition for myql2 as follows:

npm install --save-dev types/mysql2#semver:version

where version is your choice.

For example:

npm i --save-dev types/mysql2#semver:^1.0.0

Related