Joseph Jude

Technology, Psychology, and Story Telling

NPM as a build tool for Typescript projects

Posted: Tags: code,nodejs,tsc

In an earlier article, I used gulp to compile Typescript files into Javascript. Recently, I learned that I can use npm as a build tool. NPM along with package.json is sufficient enough to compile Typescript into Javascript files, watch for any changes to Typescript files and recompile.

Why use npm instead of gulp?

  • I'm already using npm while using node
  • It reduces number of dependencies. This reduces both total project size (as no more gulp modules are needed), and number of things that can go wrong.

So let me explain how I use npm as a build tool for Typescript files.

npm as build tool for typescript

Let me start with package.json. This is the default package.json when I start with npm init.

  "name": "new project",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  "keywords": [],
  "author": "",
  "license": "ISC"

I can run npm run which executes scripts in the scripts block. If I run it now, I get an error:

Lifecycle scripts included in new:
    echo "Error: no test specified" && exit 1

This is expected. Why? There is only one script mentioned, and that echos that there is no test. I'm not focusing on testing in this post. It will be a dedicated post in the Learn to build web-applications with Hapijs and Typescript series. Let me add scripts specific to Typescript now.

First is a script to compile Typescript files. This script below invokes typescript compiler.

"scripts": {
  "compile": "tsc --outDir ./build --module commonjs ./src/*.ts"

Now if I invoke, npm compile, typescript files in ./src folder will be compiled into ./build folder.

Can I start the node server automatically when the compiliation succeeds? Yes, I can. My compile command becomes:

"compile": "tsc --outDir ./build --module commonjs ./src/*.ts && node ./build/server.js"

This is fine. But whenever I change the file, I need to run npm compile. Can it watch for changes to files and invoke this command automatically?

Yes it can.

Nodemon provides the watching facility. I already use nodemon. Nodemon can watch for changes for certain file extensions and execute a command. So I'm going to add another script to the scripts block.

  "scripts": {
    "start": "./node_modules/nodemon/bin/nodemon.js -e ts  --exec \"npm run compile\"",
    "compile": "tsc --outDir ./build --module commonjs ./src/*.ts && node ./build/server.js"

If any ts files changes, then nodemon will invoke npm compile, which in turn compiles and (re-)starts the node server. Perfect.

Now I start the server with npm start and go on with my development. As I change the Typescript files, they will be compiled and server restarted automatically.

Like the post? Retweet it. Got comments? Reply.


comments powered by Disqus