Set up NodeJs Express with Typescript
Before, we start. Please make your devices has typescript and touch-cli install globally. If not, you can run command
yarn global add typescript touch-cli.
typescript— to be able to use tsc command.
touch-cli— to be able to implement the touch command for Node.
Frist, create a new nodejs project
npm init -y
It will create
Next, add dependencies
yarn add -D typescript express ts-node nodemon @types/node @types/express
typescript— to code typescript in the project.
express— to make the route for api request.
ts-node— to be able to run node app in typescript directly without the precompilation.
nodemon— to watch the server and rerun when the code changes.
@types/node— to be able to use custom typescript types for node.
@types/express— to be able to use custom typescript types for express.
Now, you can run
tsc --init to create typescript config file. Then let change target to
outDir to ./dist
After that, we create
mkdir src && cd src && touch app.ts
Before, we can test if typescript works, we need to add some commands to script.
node dist/app.js— to run the node app in javescript.
nodemon src/app.ts— to run the node app in typescript.
tsc -p .— to compile the typescript.
Next, we add basic express code to
importApplication, Request, Response from express because we already install
Now, when you run
yarn dev . We will see
You successfully run node typescript.
Finally, let build our nodejs app by running command
app.js is written in es6.
Let test running our final nodejs project’s result by running
yarn start . You will see the same result.
Congratulations, you successfully add typescript to nodejs project.
The repository for this article https://github.com/cheulong/setup-node-ts
by the author.