4

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?

Michał Lytek
  • 10,577
  • 3
  • 16
  • 24

2 Answers2

1

I think the import does not work because you are missing typescript definitions for mysql2. You have not posted your typings.json (or tsd.json) but I guess for nodejs you have imported definitions, but not for mysql2, therefore you can import 'http' using 'import from' syntax and with mysql2 you have to use plain javascript nodejs 'require' for importing it.

Amid
  • 21,508
  • 5
  • 57
  • 54
  • That explain everything, thanks! I earlier had the same problem with 'mysql' but I installed DefinetlyTyped for it and the error was gone. So I edited *d.ts for 'mysql' to 'mysql2' (since it has backward compatible API) and now it works great! – Michał Lytek Mar 18 '16 at 21:37
0

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

Hoppo
  • 1,130
  • 1
  • 13
  • 32