I installed Visual Studio Code and would like to code NodeJS using TypeScript. So I created very basic application and I get error that says:
Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.ts(2580)
Executing mentioned npm
command does not resolve the issue. I've lost the wall of links I've followed, read and either didn't apply to me, didn't fix the issue, were outdated etc.:
This one came closest:
https://www.section.io/engineering-education/how-to-use-typescript-with-nodejs/
I ran these commands:
npm i --save-dev @types/node
npm install -g typescript
npm install -D typescript
Just to test I replaced configuration file tsconfig.json
with:
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"moduleResolution": "node",
"esModuleInterop": true,
},
"exclude":[
"./node_modules"
]
}
I moved my .ts
file to src
folder of the root folder of the project, and created dest
folder. I restarted the application, nothing. I looked for extensions which might've helped, nothing.
I understand that I can't just "require" in TypeScript because it wants to check if function actually exists, unlike JavaScript. But how do I actually compile the TypeScript code to JavaScript and then run it? The lines that cause problem are the very three at the topic of the file.
const http = require('http');
const crypto = require('crypto');
const colors = require('colors');
Edit:
declare function require(name : string);
Fixed the issue. But require('crypto') throws:
lib.dom.d.ts(18699, 13): 'crypto' was also declared here.