nodejs – using typescript with nodemon

Create a new directory and run the command below in it

npm init -y

Next install nodemon with

sudo npm install -D nodemon

Add a script tag to your package.json to execute the nodemon command. This works because npm looks under node_modules/.bin for an executable. The package.json looks then like this

{
  "name": "learnnode",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "nodemon": "nodemon"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "nodemon": "^1.18.9"
  }
}

Create a new file index.js, this is the default file nodemon looks for when started without any parameters. index.js contains only:

console.log('Hello');

Now start the nodemon executable

npm run nodemon

Now if you change the index.js file nodemon will restart and execute nodejs with the new index.js file.

Now we want to make use of TypeScript. Install the typescript compiler locally together with the ts-node binary with

npm install -D typescript
npm install -D ts-node

Also add a new script to your package.json called tsc. The complete contents of the package.json file is shown below:

{
  "name": "ts",
  "version": "1.0.0",
  "description": "Example live build",
  "main": "index.js",
  "scripts": {
    "start": "npm run build:live",
    "build": "tsc -p .",
    "build:live": "nodemon --watch '*.ts' --exec 'ts-node' app.ts"
  },
  "keywords": [],
  "author": "B J de Jong",
  "license": "ISC",
  "devDependencies": {
    "nodemon": "^1.18.9",
    "ts-node": "^7.0.1",
    "typescript": "^3.2.2"
  },
  "dependencies": {}
}

Now you will need a tsconfig.json for the typescript compiler. Create a tsconfig.json file with default settings with:

npm run tsc -- --init

Now to start monitoring your ts files start the ‘start’ node script with

npm run start
Share

Leave a Reply

Your email address will not be published. Required fields are marked *