Setting up Express.js with Typescript

This article outlines how to quickly setup an Express.js server with Typescript as the compiler. It assumes you already have working knowledge of both Typescript and Express.

Intial setup

Create a new folder called express-typescript you can do this manually or through your favourite command line tool using:

mkdir express-typescript

Once this is done, enter the folder with your command line (cd express-typescript) and initialise a new package.json file by running:

npm init.

Follow the instructions that appear on screen. Once this is done your folder will now contain a fresh package.json file.

Install Express

While still in your command line and inside your project folder - run the following to install Express.js. (Note: i is just shorthand for install).

npm i express

Install Typescript

Next we'll install typescript as well as the type definitions for Express. Run the command:

npm i -D typescript @types/express

(-D tells npm to add the packages as a dev dependancy).

If you look at your package.json file, it should look something like this now - the main difference will be version numbers of the installed packages.

1// package.json
2{
3 "name": "express-typescript",
4 "version": "1.0.0",
5 "description": "",
6 "main": "index.js",
7 "scripts": {
8 "test": "echo \"Error: no test specified\" && exit 1"
9 },
10 "author": "",
11 "license": "ISC",
12 "dependencies": {
13 "express": "^4.17.3"
14 },
15 "devDependencies": {
16 "@types/express": "^4.17.13",
17 "typescript": "^4.6.2"
18 }
19}

Setting up a TS Config

If you've used Typescript before, you know that you'll need to set up a `tsconfig.json` file. The tsconfig.json file specifies the root files and the compiler options required to compile the project.

So in your root directory, create a new file called tsconfig.json and enter the following contents into it.

1{
2 "compilerOptions": {
3 "module": "commonjs",
4 "removeComments": true,
5 "sourceMap": true,
6 "target": "es6",
7 "outDir": "build",
8 "esModuleInterop": true
9 },
10 "include": ["src/**/*.ts"],
11 "exclude": ["node_modules"]
12}
13

This is a pretty basic setup and configures the bare minimum to get the project up and running with Typescript. Read more about the tsconfig options available.

Creating an index.ts

We'll now setup a a new folder called src you can do this manually again or by running the command mkdir src. This step is a personal preference, but I like to have all my scripts and project code in a folder called src that allows for easier management of the code in the future and helps to separate non-compiled code from the compiled build outputs.

Note: if you have decided to place your index.ts file inside a src directory, then you'll need to update the main property in package.json file from "main": "index.js", to "main": "src/index.js", so that the compiler knows where to find your index file.

We'll add an index file to this folder. Because we're using Typescript, you'll need to make sure you name it index.ts and not .js. This change will tell our Typescript compiler to convert this file into regular javascript in a later step.

Once you've created this file, add the following code to it.

1// index.ts
2import express, { Request, Response } from "express";
3
4const app = express();
5const port = 8080;
6
7app.get("/", (req: Request, res: Response) => {
8 res.send("Success! I'm compiled using Express and Typescript");
9});
10
11app.listen(port, () => {
12 console.log(`Example app listening on port ${port}!`);
13});

In this file we've imported Express as well as some required Types for the request and response objects. We've setup a basic home route / and also assigned a custom port to the server 8080.

Building and Developing

The final step in this basic setup is to configure the Build and Dev scripts so that we can compile the code for Production as well as work on the code locally with live updating when you make changes.

Open up your package.json again and add the following lines to the scripts object.

"scripts": {
"build": "tsc",
"dev": "ts-node-dev .",
...
}

The build script tells node to compile the files using the tsc build command which will compile your typescript files into javascript.

The dev script tells node to compile using the ts-node-dev package which is a tweaked version of node-dev that uses ts-node under the hood. This package compiles your Typescript app and automatically restarts and recompiles when files are modified. I personally found this to be superior to node-dev and nodemon which were both recommended alternatives. Whilst both work well usually, there were issues getting them to work easily with a Typescript project.

We haven't yet installed the ts-node-dev package yet. So do that now in your command line by running:

npm i -D ts-node-dev

Run the project

Now all you need to do is run the dev command to boot up your express.js server.

node run dev

If you navigate to http://localhost:8080 in your browser you should now see a success message on your screen.

Go to your `index.ts` file, change the text inside the root path, save the file and refresh your page. You should see the updated text there now.

And thats it!

Project files

You can see all the project files over on Github and can download/clone them from there if you want to skip the above.