Setting up TypeScript with NodeJS

September 3, 2022


The other day when I was setting up TypeScript with a Node project, I thought that I could write a simple guide that could help you doing this in a hopefully smooth way.

To start do the following:

First make sure that you have TypeScript installed by running or installing:

tsc -- version
npm install -g typescript
Enter fullscreen modeExit fullscreen mode

Now we need to add a package.json file:

npm init -y
Enter fullscreen modeExit fullscreen mode

To add TypeScript run the following command:

yarn add -D typescript
Enter fullscreen modeExit fullscreen mode

Next, we need to initialize our project with TypeScript. The command below will generate a file called tsconfig.json. Make sure to read and understand this file since it contains useful information and is well documented.

npx tsc -- init
Enter fullscreen modeExit fullscreen mode

Now create a new file in your project and make sure that the file extension is .ts. I will create a file called app.ts inside a src folder. Inside the file create a console.log.

src/app.ts
console.log('Hello World');
Enter fullscreen modeExit fullscreen mode

Now we need to configure so that the TypeScript files is compiled into JavaScript files. Go to the file package.json and replace the content in the scripts block with the following which will execute our TypeScript files and build them into JavaScript files.

"scripts": {
    "build": "tsc"
}
Enter fullscreen modeExit fullscreen mode

Now we can build our project and when we do this, we will get a .js file which we can use to run our application.

yarn build // to build
node app.js // to run
Enter fullscreen modeExit fullscreen mode

But this is kind of annoying to do it this way when we can run our TypeScript files directly by adding a library who handles this. Run the following command:

yarn add -D ts-node
Enter fullscreen modeExit fullscreen mode

Now go into your package.json file and the the following line in scripts:

"scripts": {
  "start": "ts-node src/app.ts",
  "build": "tsc"
}
Enter fullscreen modeExit fullscreen mode

You can delete the previously generated .js file and now directly running your TypeScript files:

yarn start
Enter fullscreen modeExit fullscreen mode

If you’re developing and want the changes to be updated each time you save, then you can add the following library which will restart the server each time you make a change:

yarn add -D ts-node-dev
Enter fullscreen modeExit fullscreen mode

Now head into the package.json file and update the scripts.start:

"scripts": {
  "start": "ts-node-dev --respawn src/app.ts",
  "build": "tsc"
}
Enter fullscreen modeExit fullscreen mode

That’s it, you have now set up TypeScript with Node.

Any comments, questions or discussions are always welcome!



Source link

Comments 0

Leave a Reply

Your email address will not be published. Required fields are marked *