This tutorial assumes you have already installed NodeJS and Typescript. If you haven't yet, there is a tutorial for each.

1. Make a directory for your project

Create a directory and cd into it for your project where you will write your code inside.

mkdir test-node-ts

cd node-ts

2. Install the required packages

You need the typescript package that is used to transpile typescript to javascript. The tslint package for linting the typescript code, and @types/node is for including the NodeJS types so typescript doesn't complain when using NodeJS libraries.

npm init -y

npm i -g typescript

npm i -D tslint

npm i -D @types/node

3. Initialize Typescript configuration and add start script to package.json

Use the tsc command to initialise and include the default tsconfig.json typescript configurations to get you started.

tsc --init

Modify the start script in package.json to include tsc && node . which means that first compile typescript to javascript then use node to run the script.

{
  "name": "test-node-ts",
  "version": "1.0.0",
  "description": "",
  "main": "dist/index.js",
  "scripts": {
    "start": "tsc && node .",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/node": "^14.14.22",
    "tslint": "^6.1.3",
    "typescript": "^4.1.3"
  }
}

That's it, you are done!


Still stuck around? Here is a bonus.

Nodemon

You can use nodemon npm package to automatically reload everytime your typescript script changes.

Start by installing ts-node which is a typescript executer and REPL for NodeJs, and nodemon which is a script monitor for node js

npm i -D ts-node nodemon

Then configure nodemon in a nodemon.json file in the root of your project.

{
  "restartable": "rs",
  "ignore": [".git", "node_modules/", "dist/", "coverage/"],
  "watch": ["src/"],
  "execMap": {
    "ts": "node -r ts-node/register"
  },
  "env": {
    "NODE_ENV": "development"
  },
  "ext": "js,json,ts"
}

The configuration includes:

  • restartable — a command we can use to restart the program manually when the script is running and waiting for changes
  • ignore — the list of files that should not trigger restart when they are changed
  • watch — list of paths that we want to listen for changes
  • execMap — map a file to a runtime
  • env — environment variables that should be included
  • ext — the file extensions Nodemon monitores

Let's modify the package.json and include the following script:

"scripts": {
    "dev": "nodemon --config nodemon.json src/index.ts"
 }

Now we can run the program with npm run dev to start executing and listening for changes.

Using template

You can clone or fork this basic template and start using for however you like 😉