Skip to content
thesarfo

Note

Setting Up Node.js with TypeScript

Initializing a Node project with TypeScript, compiling with tsc, and switching to ts-node so you don't have to juggle a dist folder.

views 0

First initialize your node project with npm using

Terminal window
npm init -y

And then create an “index.ts” file which is going to be the entry point for your server. dont forget to change the “main” in your packagejson file to “index.ts”

To make your node project use typescript, you need to initialize the project with typescript as well, using the below command

Terminal window
npx tsc --init

This command will generate a tsconfig.json file in your root directory

You can use the command tsc index.ts to compile the index.ts file and you will notice that the same file will be created but in javascript, this means that the typescript has been compiled into normal javascript. That’s how typescript works.

But we dont want to create an extra copy of our file whenever typescript compile it, so what we can do is that we can create a separate folder in which we will store those compiled files. This folder will be called “dist”.

Now you need to specify in your tsconfig.json that you want to store your compiled files inside the “dist” folder, so open the tsconfig.json, and then search for “outDir”. And then specify the folder to be ”./dist”.

Note that your server project COULD be stored in another folder called “server” - so go ahead and create that folder

Now you can run your index.ts file with just the “tsc” command and you will see that a compiled version will be stored in the “dist” folder

Assumming you are trying to import a node module and you get an error that typescript doesnt know where the module is coming from, you can use the command npm i @types/node -D to fix it, tho it will be installed as a development dependency. This command basically installs node so you will get a package.json file

If you want to compile the compiled javascript code and then run the code to see the results you need to specify it in your package.json file. see below

"scripts": {
"start": "tsc && node dist/index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},

Now when you run “npm run start” it will compile the index.js and then display the results in the console

Now there is actually a package called “ts-node” that runs typescript code directly without having to use the dist folder and the double command in the start inside the package.json script. install the package by using

Terminal window
npm install ts-node -D

And then inside your package.json file, just change the start script to

"scripts": {
"start": "ts-node server/index.ts",
"test": "echo \"Error: no test specified\" && exit 1"
},

Now when you run npm run start, it will compile the code for you, without changing it to javascript first.

Now you can delete the “dist” folder and start coding.