DEV Community

Cover image for Express with TypeScript and TypeOrm. Part 1
Francis Gyimah
Francis Gyimah

Posted on • Edited on

Express with TypeScript and TypeOrm. Part 1

Setting up an express server with TypeScript can be daunting at first. In the first part of this 2-part series, we will look at how to set up a professional express TypeScript project from scratch. We will set up the base folder structure and also the base express setup. We will then look at how to connect to our database(PostgreSQL) in this case in the second part. Let's begin.

To set up an express project you need to have nodeJS installed locally on your machine, this can be downloaded from here. This also gives you access to a very important CLI tool called NPM (Node Package Manager). Using NPM we can add packages from the NPM registry into our project.

Verify that NodeJS is installed on your machine by typing

node --version

A version should be printed indicating NodeJS is successfully installed on your computer.

We create an empty directory that will hold all of our project’s code. I’m going to name mine express-typescript but feel free to use whichever name you want.

mkdir express-typescript && cd express-typescript

Inside this folder, we initialize a new npm project by typing

npm init -y

The -y flag is to tell NPM to give us the default configuration. We then install express as well as the types for express and the typescript compiler along with other helper libraries.

npm install --save express 
npm install --save-dev @types/node @types/express typescript nodemon ts-node

Typescript is what helps our application transpile the typescript programming language into JavaScript. Ts-node allows us to run typescript files directly without having to transpile them first, this is great for development mode. Nodemon automatically watches for changes within our project and restarts the server without having to do that manually.

Next off, we’ll create a tsconfig.json file to tell the typescript compiler how to compile our code. We add the following options into the tsconfig.json file

{
  "compilerOptions": {
    "target": "esnext",
    "module": "commonjs",
    "sourceMap": true,
    "outDir": "./dist",
    "removeComments": true,
    "moduleResolution": "node",
    "noImplicitAny": false,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "noImplicitThis": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,

    //add decorator support
    "allowSyntheticDefaultImports": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true
  },
  "include": ["./src/**/*.tsx", "./src/**/*.ts"],
  "exclude": ["node_modules"]
}

We modify our package.json with the following code

{
  "name": "express-typescript",
  "version": "1.0.0",
  "description": "Typescript with express tutorial",
  "main": "index.ts",
  "author": "Francis Gyimah <fgyimah883@gmail.com>",
  "license": "MIT",
  "private": false,
  "scripts": {
    "start": "node ./dist/index.js",
    "start:dev": "nodemon",
    "build": "tsc"
  },
  "dependencies": {
    "express": "^4.17.1",
  },
  "devDependencies": {
    "@types/express": "^4.17.6",
    "@types/node": "^13.13.0",
    "nodemon": "^2.0.3",
    "ts-node": "^8.8.2",
    "typescript": "^3.8.3"
  }
}

We have included 3 scripts into our server and these are:

  • start: This is to tell how we want to start our server in production mode, the compiled javascript will be in the dist folder and we are telling node to run our javascript file from there
  • start:dev: This is how we start our development server, by default, nodemon will look for a file called nodemon.json to run whenever this command is called. We’ll create that in the next step
  • build: this is how we build or transpile our TypeScript code into JavaScript using the tsc command, which we get as a result of installing the typescript dependency.

To configure nodemon we create another file in the root directory of our project called nodemon.json, and add the following code to it

{
  "watch": ["./src/**/*", ".env"],
  "ext": "ts",
  "exec": "ts-node ./src/index.ts"
}

This tells nodemon to watch for changes in the src directory, where our actual code is going to live and also watch the .env file, which is a special file where all our sensitive information like API keys is going to live. We also watch all files with the .ts extension, meaning all typescript files in the src folder. The exec tells nodemon the command to run which is ts-node command and our main script is the index.ts file inside the src folder.

We create the src folder and the index.ts file in it

We create a base express server using the following code snippet

import * as express from 'express';

const app = express();

//configure application routes
//@GET - dummy api route
//@ts-ignore
app.get('/api', (req, res, next) => {
  res.status(200).json({
    hello: 'World!',
  });
});

const port: Number = Number(process.env.PORT) || 3000;
const startServer = async () => {
  await app.listen(port, () => {
    console.log(`Server running on http://localhost:${port}`);
  });
};

startServer();

That’s it, we now run the following command in the terminal

npm run start:dev

and go to https://localhost:3000/api to see our result.

In the next part, we’ll look at configuring environment variables and how to connect to a PostgreSQL database using typeOrm

Top comments (2)

Collapse
 
himharsh1997 profile image
Himanshu Joshi

thanks

Collapse
 
rinsama77 profile image
imrinzzzz • Edited

this is nice! thank you. Btw, I see this is a 2-post series, you can use dev.to's series function.