Setup Node/Express with TypeScript
Tags: typescript, node, javascript, productivity
Published: 2020-05-19 15:38:17

Hello All,

In this blog we are going to learn how to setup Node/Express with TypeScript for awesome backend development workflow with good folder structure as bonus.


# Dependencies Installation
You should have Node.js installed in your dev machine.(Why wouldn't you?)
We will install other dependencies when it will be required.

Firstly, we need to initialize `npm` project
```bash
 npm init -y
```

Secondly, we need Express and Cors as our production dependency
```javascript
 npm i express cors
```

Now since we have the basic setup ready let's start main part for which you are reading this blog!

We need to install typescript, nodemon(for restart on save), ts-node(to run typescript file using node compiler) package.

```javascript
 npm i -D typescript nodemon ts-node
```



# Folder Structure

For reference please visit one of my [project on Github](https://github.com/AryanshMahato/merch-shop-api) 

We need to create `src` folder which will contain whole codebase(just like react)

`build` Directory will be generated by TypeScript(Reference at bottom of this blog).

*You can also create `types` folder containing all interface and types of the project.



# TypeScript Configuration

We need to setup TypeScript Configuration to build application for production use.(as typescript will not be needed in production)

```javascript
tsc --init
```

This command will generate a `tsconfig.json` file, with all default typescript configuration.

We just need to edit our rootDir and outDir in `compilerOptions`

```json
{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig.json to read more about this file */

    /* Basic Options */
    // "incremental": true,                   /* Enable incremental compilation */
    "target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
    "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
    // "lib": [],                             /* Specify library files to be included in the compilation. */
    // "allowJs": true,                       /* Allow javascript files to be compiled. */
    // "checkJs": true,                       /* Report errors in .js files. */
    // "jsx": "preserve",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
    // "declaration": true,                   /* Generates corresponding '.d.ts' file. */
    // "declarationMap": true,                /* Generates a sourcemap for each corresponding '.d.ts' file. */
    // "sourceMap": true,                     /* Generates corresponding '.map' file. */
    // "outFile": "./",                       /* Concatenate and emit output to single file. */
    // "outDir": "./",                        /* Redirect output structure to the directory. */
    // "rootDir": "./",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    // "composite": true,                     /* Enable project compilation */
    // "tsBuildInfoFile": "./",               /* Specify file to store incremental compilation information */
    // "removeComments": true,                /* Do not emit comments to output. */
    // "noEmit": true,                        /* Do not emit outputs. */
    // "importHelpers": true,                 /* Import emit helpers from 'tslib'. */
    // "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
    // "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

    /* Strict Type-Checking Options */
    "strict": true,                           /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,              /* Enable strict null checks. */
    // "strictFunctionTypes": true,           /* Enable strict checking of function types. */
    // "strictBindCallApply": true,           /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
    // "strictPropertyInitialization": true,  /* Enable strict checking of property initialization in classes. */
    // "noImplicitThis": true,                /* Raise error on 'this' expressions with an implied 'any' type. */
    // "alwaysStrict": true,                  /* Parse in strict mode and emit "use strict" for each source file. */

    /* Additional Checks */
    // "noUnusedLocals": true,                /* Report errors on unused locals. */
    // "noUnusedParameters": true,            /* Report errors on unused parameters. */
    // "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
    // "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */

    /* Module Resolution Options */
    // "moduleResolution": "node",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    // "baseUrl": "./",                       /* Base directory to resolve non-absolute module names. */
    // "paths": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
    // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
    // "typeRoots": [],                       /* List of folders to include type definitions from. */
    // "types": [],                           /* Type declaration files to be included in compilation. */
    // "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
    "esModuleInterop": true,                  /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    // "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */
    // "allowUmdGlobalAccess": true,          /* Allow accessing UMD globals from modules. */

    /* Source Map Options */
    // "sourceRoot": "",                      /* Specify the location where debugger should locate TypeScript files instead of source locations. */
    // "mapRoot": "",                         /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
    // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

    /* Experimental Options */
    // "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
    // "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */

    /* Advanced Options */
    "skipLibCheck": true,                     /* Skip type checking of declaration files. */
    "forceConsistentCasingInFileNames": true  /* Disallow inconsistently-cased references to the same file. */
  }
}
```

This will be the generated `tsconfig.json` file,
Uncomment `rootDir` and `outDir` and write their value like this.

```json
 "outDir": "./build",                        /* Redirect output structure to the directory. */
 "rootDir": "./src",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ 
```

When Running build command(will create that later on this post), TypeScript compiler will generate compiled JavaScript in build folder code to run on server.



# Installing Packages(TypeScript Way)

We always install `npm` packages with there type annotation while using TypeScript. Some packages contains TypeScript Annotation by default, But for most of packages we need to install `@types/package-name`.

You can search on [npmjs](https://npmjs.com) to confirm if @types annotations are present or not for your desired package.


So, To Create a Simple server we need to install few packages.

```javascript
 npm i -D @types/express @types/cors
```



# Creating `express` server

Create a `App.ts` file in `/src/` directory, and copy the code snippet to create a basic `Hello World` server.

```javascript
import express, { Request, Response } from "express";
import cors from "cors";
const app = express()

app.use(cors());

app.get("/", (req: Request, res: Response) => {
  res.status(200).send("Hello World!");
})

app.listen(8000,()=>{
  console.log('Server Started at Port, 8000')
})
```

Yes, With TypeScript we can use ES6 modules in Node.js also..



# Creating `npm` commands

We need to create `npm` commands to compile or run our Project,

First, Edit `package.json` file and add these lines in `scripts:{}` object.

```json
"scripts": {
    "devStart": "nodemon ./src/App.ts",
    "start": "node ./build/App.js",
    "build": "tsc"
  }
```

`devStart`: Will run a Development server with reload on save using nodemon.
`start`: Will run Production server with build(compiled) JavaScript code.
`build`: Will generate compiled JavaScript code from TypeScript code.

** Remember, You must build your project before starting production server.



# Running our App

Now, Everything is perfect(hopefully😅).
We are all set to run our app.

`Open Terminal` and type:

```javascript
 npm run devStart  //To run development server(with auto reload on save)

 npm run build     //To compile TypeScript code in JavaScript

 npm start         //To run production server(with compiled JavaScript Code)
```



# Final Talks..

Your Project Folder Structure should Look like this,
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/2juvvdkz7v29br1s6pz5.PNG)

`If everything went perfect, then your server should be running now`





Comment any feedbacks please, follow me on [LinkedIn](https://www.linkedin.com/in/aryansh-mahato-a4b33015a/)