i'm using Visual Studio Code for NodeJS and Typescript development. If I'm writing this code:
import * as http from 'http';
The compile says error TS2307: Cannot find module 'http'.
How to handle this error?
Greetz
If you are getting the "Cannot find module" error when trying to run a local file, make sure that the path you passed to the node command points to a file that exists. For example, if you run node src/index. js , make sure that the path src/index. js points to an existing file.
This worked for me:
npm install @types/node --save
I realise it's been a while since the OP, however this is a more updated answer in case someone stumbles across this problem.
This error occurs in Typescript because the http
and the other modules of Node.js are written in Javascript. The Typescript compiler doesn't have information about the types and modules of libraries that are written in Javascript. To add this information, you need to include type declarations for the Node.js in your Typescript project.
Execute the following terminal command in your project's root directory:
npm install -D @types/node
That's it! Now the error should disappear.
The above command will download type declaration files (.d.ts
) for the Node.js. Now you can see the files in the directory ./node_modules/@types/node
of your project and http.d.ts
is one of them. In this file, you'll find declarations for the http
module and all the types such as IncomingMessage
, ServerResponse
and others that are used in the HTTP server. This is how Typescript compiler and VS code use type declaration information to provide you with the type safety.
@types:
There is a community maintained repository called
DefinitelyTyped which contains type declaration files for a lot of old and new Javascript libraries such as Express, Sequelize, JQuery and many others. When you specify the @types
package in your command, it means you are downloading the declaration types from the DefinitelyTyped repository.
-D flag:
The command will also automatically add the types for the Node.js in the devDependencies
section of your package.json
file as shown in the following code snippet:
{
...
"devDependencies": {
...
"@types/node": "^14.0.27"
}
}
The -D
flag ensures that the types go in the devDependencies
section of the package.json
file instead of the dependencies
section. Because this package is required only in development not in production. Do not use --save
flag as mentioned in other answers, because it adds the types dependency in the dependencies
section of the package.json
and bloats the server installation with unnecessary files.
That's it!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With