This post will explain how to setup up a basic hello world express app with typescript, we will be using pnpm as the package manager.
Table of contents
Open Table of contents
Basic Project Setup
Initialize the Project
Initialize the folder as a pnpm project
Installing Packages
Install typescript and type declarations for node as dev dependencies.
Install TSX as the typescript runner.
Install Express with it’s typings.
Configuring Typescript
We will be using ESM (ECMA Script Module) syntax. So, we need to add an extra property called type with value as module to package.json
Then add a tsconfig.json file to the root of project
You can use your own tsconfig.json file or checkout a cool repo called @tsconfig/bases.
Loading Env Variables
We will be using dotenv
for loading variables from .env file, and zod
for parsing and validating the env variables.
Creating a file to load ENV variables.
This will load env variable a .env
file which looks something like this,
Writing the Server
This is a basic hello world server. We are importing PORT from this env.ts
file we just made.
Now, we can use tsx
to run typescript file directly without manual transpilation.
Building the Project (OPTIONAL)
We can use tools like esbuild
to bundle the entire code to a single js file, which we can run directly with Node.
Then setting up a custom build script to bundle .ts
files with ESM syntax to .mjs
file with ESM Syntax. We also need toi include a custom header for now because of an issue with esbuild.
For compiling the source code use the command below. This will create a dist folder with index.mjs
file in it.
After compiling everything to a single file we can run it like this,
It doesn’t even need any of the external dependencies to be installed, which is super cool 😎