Check out myAngular article series with live demos and Facebook group Angular - Advanced Topics

Using TypeScript With NodeJs

Torgeir "Tor" Helgevold
- JavaScript Developer and Blogger
Published: Sun Mar 11 2018

Lately I have started to combine Typescript more and more with nodejs coding. In this post I will show how to incorporate Typescript into a nodemon based workflow.

Why bother with Typescript in Node?

In my opinion it comes down to personal preference. I think it’s perfectly fine to develop your node application using regular Javascript if you’re not a fan of Typescript.

However, I am already doing all my Angular development in Typescript. Adding Typescript to the server code feels like a natural extension.

Not only does it give me a consistent coding pattern, but it also opens the door to sharing types and interfaces between client and server.

My blog is implemented as an express app written in regular JavaScript. It’s a decent size app, so it’s not an option to convert all my existing code to Typescript. Instead I want the existing Javascript code to coexist with any new code written in Typescript.

This is not an issue since Typescript ultimately compiles down to regular Javascript.

Nodemon

I am used to using nodemon to refresh my node app every time I make a change to the source.

How does Typescript compilation integrate with nodemon?

Luckily this is pretty easy since nodemon allows you to execute custom tasks for every change.

The base command I use is:

nodemon --exec 'node_modules/.bin/ngc && node server.js'

This tells nodemon to rerun the –exec command every time there is a file change.

In my case I am using the ngc compiler since I am doing Angular AoT compilation. However, for plain Typescript you would substitute ngc for tsc.

To simplify the nodemon command, I’ve moved the watch configurations to a separate nodemon.json file:

nodemon.json
{ "restartable": "rs", "ext": "js,ts,html", "ignore": ["dist"], "watch": ["./angular-server", "./services", "server.js"] }

This tells nodemon which folders and file extensions to watch. There is also a command to force a restart (typing rs in the console will restart).

Depending on your application you may also need a tsconfig file to guide the Typescript compiler.

My sample file can be found below:

tsconfig.json
{ "compilerOptions": { "target": "es6", "module": "commonjs", "moduleResolution": "node", "emitDecoratorMetadata": true, "experimentalDecorators": true, "lib": ["es2015", "dom"], "outDir": "dist" }, "include": ["angular-server"], "exclude": ["dist"], "angularCompilerOptions": { "annotateForClosureCompiler": true, "skipMetadataEmit": true } }

If you liked this article, share it with your friends on social media:

We also have a new Facebook group about advanced Angular topics.

I invite you to follow me on twitter