Setting Up TypeScript for Node

Sat Jun 01 2019

Photo by Samuel Sianipar on Unsplash

Today, I wanted to go over how to set up a TypeScript project for NodeJS from scratch.

It's something that I do fairly often and so it's nice to have this as a starter repo for some of my future NodeJS projects.

Let's first create a new directory for this project. I'll just call it ts-node-demo for now, but you can just rename it at a later date when you use it to start a new project.

mkdir ts-node-demo
cd ts-node-demo

Let's make this a git repository and use yarn for our package manager. It'll be a good idea not to commit any of our dependencies into our repo as well.

git init
yarn init
echo node_modules/ > .gitignore

Now I'll add the most basic dependencies for our TypeScript NodeJS project. Rather than doing an explicit build step and then running the plan JavaScript file that is a result of that build, I want to use the ts-node library that will take care of that for me. I'll, of course, also add TypeScript as well as the type definitions for NodeJS.

yarn add ts-node typescript @types/node

It'll be nice if I didn't have to restart the dev server everytime I save a file so let's add ts-node-dev. If you've ever worked with nodemon, this is pretty much the same, but for TypeScript.

yarn add -D ts-node-dev

package.json

{
  "name": "ts-node-demo",
  "version": "1.0.0",
  "main": "index.js",
  "author": "Warren Wong<me@warrenwong.org>",
  "license": "MIT",
  "dependencies": {
    "@types/node": "^12.0.4",
    "ts-node": "^8.2.0",
    "typescript": "^3.5.1"
  },
  "devDependencies": {
    "ts-node-dev": "^1.0.0-pre.39"
  }
}

I'll update the package.json to reflect the change to using TypeScript by changing index.js to index.ts. I should go ahead and create that file as well.

touch index.ts

Now let's add some scripts for starting the production app as well as starting the dev server. Since a service like Heroku would use yarn start or npm start to start the production server, I'll go ahead define "start" as "yarn ts-node index.ts". To start the dev server, I want to just type yarn dev, so I'll define "dev" as "yarn ts-node-dev index.ts".

package.json

{
  "name": "ts-node-demo",
  "version": "1.0.0",
  "main": "index.ts",
  "author": "Warren Wong <me@warrenwong.org>",
  "license": "MIT",
  "dependencies": {
    "ts-node": "^8.2.0",
    "typescript": "^3.5.1"
  },
  "devDependencies": {
    "@types/node": "^12.0.4",
    "ts-node-dev": "^1.0.0-pre.39"
  },
  "scripts": {
    "start": "yarn ts-node index.ts",
    "dev": "yarn ts-node-dev index.ts"
  }
}

Now to check if everything worked out, I'll need index.ts to actually do something.

index.ts

console.log("Hello, World!");

Okay, time to test this out.

yarn dev
Using ts-node version 8.2.0, typescript version 3.5.1
Hello, World!
yarn start
Hello, World!

If you found the post helpful and would like this same content delivered to you,

Subscribe to my newsletter

;