Codementor Events

How To Setup a Basic TypeScript Server

Published Jan 27, 2019

In this tutorial, I am going to show you how to get up and running with a basic typescript server, capable of watching, and compiling on file change.

First, lets initiate our project with NPM or Yarn (I prefer yarn, but it dosen't really matter which one you use.) Go into your directory, and if you are using NPM type this:

npm init

If your using yarn:

yarn init

Then, fill in the fields it asks you for. A lot of the time, you can just skip through most of the options, but I would reccomend putting in a License, especially if it's an open source project.

Next, we'll install some new packages to get the server working:
If you are using NPM:

npm install ts-node nodemon typescript --dev

If you are using Yarn:

yarn add ts-node nodemon typescript --dev

Next, lets make a tsconfig.json, this is the configuration file TypeScript uses when compiling. The official TypeScript docs has a much better tutorial then any one I could make, so I would reccomend using this for this step: here.

Next, lets make our src folder. To do this, lets create a folder called "src". This stands for "source", and it's where all of our source code will go. Lets make a file called index.ts - This will be the entry point for all our files.

Now lets setup our package.json. It should already have been created, so lets open it up in our favorite editor, and lets write some scripts. First, lets set up the start script. This will re-run your code every file change, making productivity significantly smoother. To do this, lets add this to our package.json:

"scripts": {
  "start": "nodemon --exec ts-node src/index.ts"
}

Basically what this is doing is it's listening for file changes, then running the index.ts file.

The final step is to setup a build script! To do this, we will add one line to the "scripts" section of package.json, add this:

"build": "tsc"

and thats it! Thats all you have to do! If you have any other problems feel free to add me on Discord: Haxified#0311.

Discover and read more posts from Robert Westbury
get started