DEV Community

m0nm
m0nm

Posted on

How to set up Typescript with Express JS

Today I'm going to show you how to create an Express js project with Typescript as fast as possible.

follow these steps:

  • Create the project folder and navigate to it by running the following commands:
    mkdir express-typescript
    cd express-typescript

  • Initiate the project:
    npm init -y

  • Install these dev dependencies (Note the -D flag)
    npm i typescript ts-node @types/node @types/express -D

Your package.json should have this inside:

"devDependencies": {
    "@types/express": "^4.17.9",
    "@types/node": "^14.14.20",
    "ts-node": "^9.1.1",
    "typescript": "^4.1.3"
  },
Enter fullscreen mode Exit fullscreen mode
  • Now initialize typescript:
    npx tsc --init
    the command will create a tsconfig.json file. The file will contain the configuration for typescript. The ones we're interested in are:

  • target: this specifies wich ECMAScript version is used in your project, default to es2016

  • module: specifies which module is used to generate javascript code, defaults to commonjs, You can choose each of this: none, commonjs, es2015, es2020, or ESNext.

  • outDir: specifies the output location of the vanilla javascript code. It's commonly used to place it inside the build folder: "outDir": "/build/"

  • rootDir: specifies the location of the typescript code, default to ./

  • strict: enable/disable the strict mode, default to true

You're now done ! after you finish your project you can run the command npx tsc.

Alternatively , You can create a script to run the command, In your package.json inside the scripts object type:

"scripts": {
    "build": "npx tsc"
}
Enter fullscreen mode Exit fullscreen mode

I hope this post was helpful. Happy coding!

Top comments (0)