Welcome!
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
Now we need to add a package.json file:
npm init -y
To add TypeScript run the following command:
yarn add -D typescript
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
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');
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"
}
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
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
Now go into your package.json
file and the the following line in scripts
:
"scripts": {
"start": "ts-node src/app.ts",
"build": "tsc"
}
You can delete the previously generated .js
file and now directly running your TypeScript files:
yarn start
Bonus
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
Now head into the package.json
file and update the scripts.start
:
"scripts": {
"start": "ts-node-dev --respawn src/app.ts",
"build": "tsc"
}
Summary
That’s it, you have now set up TypeScript with Node.
Any comments, questions or discussions are always welcome!