Getting setup with Express and TypeScript
A quick walk through of getting setup up with Node, Express and TypeScript
Planted October 21, 2023
Last tended November 17, 2023
Setting up a Node.js and Express backend with TypeScript can seem intimidating, but it’s quite straightforward once you break it down. Here’s a step-by-step guide to get you started:
- Initialize a New Node Project:
- Install Required Packages:
-
typescript
is the TypeScript compiler. -
@types/node
and@types/express
provide TypeScript type definitions for Node.js and Express, respectively. -
ts-node
lets you run TypeScript directly without compiling it to JavaScript first. -
nodemon
watches for file changes and restarts your server. You can use Node’s built in watch mode flag (--watch
) but check your version of Node first.
3. Initialize TypeScript Configuration:
This will create a tsconfig.json
file. Adjust the following settings in this file:
These settings specify that:
-
Your TypeScript code uses ES6 features and CommonJS modules.
-
The compiled JavaScript will be output to a
dist
directory. -
Your source TypeScript files will be inside a
src
directory.
4. Setup Nodemon for Development:
In your package.json
, add the following scripts:
- Write Your TypeScript Express App: Create a
src
directory and inside it, createindex.ts
:
- Run Your App:
Now, if you visit http://localhost:3000/
, you should see the message “Hello from TypeScript backend!“.
- Production Build:
If you want to compile your TypeScript code for production, you can add a build script to yourpackage.json
:
Running npm run build
will now compile your TypeScript code to JavaScript in the dist
directory.
With these steps, you should have a basic setup for a Node.js, Express, and TypeScript backend. As your application grows, you might want to add additional tooling, middleware, and types to further enhance your development experience.