Introduction
Express is a popular web framework for Node.js that makes it easy to build APIs and web servers. It handles routing, request/response handling, and much more, so we can focus on our application’s logic.
Why use Express?
- Simple and minimal
- Large community and lots of resources
- Works well with TypeScript
Installing Express
- Create a new project folder:
mkdir express-api cd express-api code . # to open in VSCode - Initialise a new Node.js project:
npm init -y - Enable ES modules in package.json:
Add
"type": "module"to yourpackage.jsonfile:{ "name": "express-api", "version": "1.0.0", "type": "module", "main": "index.js" } - Install Express and TypeScript:
npm install express npm install --save-dev typescript @types/node @types/express tsx -
Create a basic TypeScript config:
npx tsc --initThe
tsconfig.jsonfile is the configuration file for TypeScript. It tells the TypeScript compiler how to process our code — what language features to use, where to find our source files, where to put the compiled output, and how strict the type checking should be. Adjusting this file helps ensure our project works smoothly with TypeScript and Express.In the generated
tsconfig.json, find and update these settings:{ "compilerOptions": { "target": "ES2020", "module": "ES2020", "moduleResolution": "node", "outDir": "./dist", "rootDir": "./src", "strict": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true } } - Create a
srcfolder and our entry file:mkdir src touch src/index.ts