Starting with a tech stack and not sure how to get your project going? Well, we have all been there at some point in time. In this tutorial, we will create a simple TypeScript app using NodeJS and Express Web Framework. This is a simple output we will expose over port 3000. Follow the steps below to create the NodeJS TypeScript project with me.
1.1 Create Directory And Initialize The Node Project
Create a directory anywhere or possibly where you store all your git repos and call it anything of your choosing but for the sake of this tutorial I am going to call mine app-example
. Run the following command to initiate your node project with Yarn:
yarn init -y
1.2 Configure the TypeScript Compiler
To install typescript run the following command to add it to your project:
yarn add typescript
Next create the tsconfig.json
file in the root of your directory and add the typescript config below:
{
"compilerOptions": {
"module": "commonjs",
"esModuleInterop": true,
"target": "es6",
"moduleResolution": "node",
"sourceMap": true,
"outDir": "build"
},
"lib": ["es2015"]
}
1.3 Build A Minimal Express Server With TypeScript
Add the express web module to your node project by running the commands in your cli below:
yarn add express
yarn add @types/express
yarn add @types/node
Create a src
directory in the root of your project and inside that directory create a file called index.ts
and copy the code below to that file.
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('This is an example node server');
});
app.listen(port, () => {
console.log(`[server]: Server is running at http://localhost:${port}`);
});
In your terminal run this command node src/index.ts
which will start your node server and output the following:
[server]: Server is running at http://localhost:3000
Or you can navigate to this address http://localhost:3000
in your browser and you should see this text in your browser:
This is an example node server
1.4 Add Nodemon For Live Development
We are going to add nodemon and ts-node to the project for live coding meaning we will not have to restart our application for changes to execute instead nodemon will handle it for us. Run the following command to add nodemon to your project:
yarn add ts-node
yarn add -D nodemon
Next, we will add the script below to package.json
so when we run yarn start
our development is live and nodemon will do the hot reload work in the background as you code.
"scripts": {
"start": "nodemon --watch \"*.ts\" --exec \"ts-node\" ./src/index.ts",
},
Run yarn start
and start working on your project.
Conclusion
In conclusion, this is a good starting point if you want to create a new NodeJS project with TypeScript. If you enjoyed this article consider signing up for our newsletter and don't forget to share it with people who would find it useful. Leave a comment below with a tutorial you would like us to cover.