Using TypeScript with Node.js: A Guide to Building Robust Server-Side Applications
Tags: node, typescript
Published: 2023-12-06 07:11:40

Enable the power of types in your Node.js application with TypeScript! In this guide, we will explore the seamless integration of TypeScript into the Node.js environment, unlocking the potential for building robust and maintainable server-side applications. Whether you're a seasoned developer or just starting with Node.js, this article is your go-to buddy for elevating your coding experience and enhancing the scalability of your projects.

## Getting Started
Let's kick things off by initializing our NPM project:

`bash
npm init -y`
Simply press ENTER to go through the configuration steps. Now, let's install TypeScript in our project:

`bash
npm install --save typescript`
To enable running TypeScript commands, add the tsc command to your package.json scripts:

`json
{
  "scripts": {
    "tsc": "tsc",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "dependencies": {
    "typescript": "^5.2.2"
  }
}`
Next, initialize the TypeScript project and generate the tsconfig.json file:

`bash
npm run tsc -- --init`
Your tsconfig.json file will be generated with default settings. For further customization, you can use the following options:

**Linux:**
`bash
npm run tsc -- --init --target esnext --module nodenext \
--moduleResolution nodenext --rootDir src \
--outDir dist --noImplicitAny --noImplicitThis --newLine lf \
--resolveJsonModule`

**Windows:**
`bash
npm run tsc -- --init --target esnext --module nodenext `
--moduleResolution nodenext --rootDir src `
--outDir dist --noImplicitAny --noImplicitThis --newLine lf `
--resolveJsonModule`

## Understanding tsconfig.json
The tsconfig.json file contains configurations for the TypeScript compiler. Apart from compilerOptions, you can customize:

- files: Specifies files included in the build.
- include: Determines which files/patterns should be included in the build.
- exclude: Specifies files/patterns to be excluded from the build.
- extends: References another tsconfig.json file.
- watchOptions: Configures behavior for tsc --watch.
- references: Splits configurations into multiple pieces.
For a detailed look at all configurations, refer to the tsconfig documentation.

## Using Existing TypeScript Configurations
Utilize existing configurations with the extends option. For example:

`json
{
  "extends": "@tsconfig/node12/tsconfig.json",
  "compilerOptions": {
    "preserveConstEnums": true
  },
  "include": ["src/**/*"]
}`
Check recommended bases for more options.

## Project Compilation and Execution
Set up a small project by creating a src folder and an index.ts file. Run npm run tsc to compile TypeScript code into JavaScript. Use npm start for an optimized build and execution process:

`json
{
  "scripts": {
    "tsc": "tsc",
    "build": "rimraf dist && tsc",
    "start": "ts-node src/index.ts"
  },
  "devDependencies": {
    "rimraf": "^5.0.5",
    "ts-node": "^10.9.1"
  }
}`

## Optimizing Build Steps
Enhance build steps by automating file deletion with rimraf. Install it with:

`bash
npm i -D rimraf`
Add a dedicated build step to package.json:

`json
{
  "scripts": {
    "build": "rimraf dist && tsc"
  }
}`

## Automatic Restart with Watch Mode
Enabling watch mode for automatic restarts during development is crucial. Use ts-node and nodemon for an efficient workflow. Install them:

`bash
npm i -D ts-node nodemon`
Add the following configurations to nodemon.json:

`json
{
  "watch": ["src"],
  "ext": ".ts,.js",
  "ignore": [],
  "exec": "ts-node ./src/index.ts"
}`
Update package.json with a watch script:

`json
{
  "scripts": {
    "watch": "nodemon"
  },
  "devDependencies": {
    "nodemon": "^3.0.1",
    "rimraf": "^5.0.5",
    "ts-node": "^10.9.1"
  }
}`
Now, run npm run watch for automatic restarts during development.

## Third-Party Libraries Support
When using third-party libraries like Express, add type support with @types:

`bash
npm i -D @types/express`
Update package.json:

`json
{
  "dependencies": {
    "express": "^4.18.2",
    "typescript": "^5.2.2"
  },
  "devDependencies": {
    "@types/express": "^4.17.21",
    "nodemon": "^3.0.1",
    "rimraf": "^5.0.5",
    "ts-node": "^10.9.1"
  }
}`

## Conclusion
This guide has walked you through the process of setting up TypeScript with Node.js, providing tips and tricks for optimizing your development workflow. From initiating a new NPM project to configuring TypeScript with tsconfig.json, and even handling third-party libraries like Express, you're now equipped to elevate your coding game. Whether you're a seasoned developer or just starting, TypeScript and Node.js offer a powerful combination for building scalable server-side applications.