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 by running:
tsc -v
If you need to install TypeScript run:
yarn add typescript
Now we need to add a package.json file. In your project folder:
yarn init -y
To add TypeScript run the following command:
yarn add -D typescript @types/node
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.
yarn 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.
mkdir src
touch src/app.ts
Add console.log('Hello World');
inside app.ts.
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"
}
Now run:
yarn start
Develop and save and your changes will appear automatically without having to build each time.
Summary
That's it, you have now set up TypeScript with Node.
Any comments, questions or discussions are always welcome!
β
Top comments (0)