Setting up a Typescript Node App
Tags: typescript, node
Published: 2023-11-07 18:29:58


Setting up a Node project feels like a daunting task? Well, fear not! Our friend [Matt Pocock](https://www.totaltypescript.com/build-a-node-app-with-typescript-and-esbuild) has got you covered with a fantastic article that walks you through the process.

Matt's article is incredibly straightforward, making it a great starting point. However, you might feel that it lacks some essential features like code formatting, linting, and unit testing. Don't worry; we've got you covered! Let's dive in and add these crucial components to your Node project.

## Pre-requisites

Before we dive into the nitty-gritty details, let's set some prerequisites in place. First up, let's add a git-hook to catch those pesky commit errors. We'll be using [Husky](https://typicode.github.io/husky/) for this purpose. Follow these simple steps to get started:

- Check out the [Husky getting started guide](https://typicode.github.io/husky/getting-started.html#manual).
Next, we'll introduce [lint-staged](https://github.com/lint-staged/lint-staged) into the mix. Execute the following commands:

```bash
npm install --save-dev husky lint-staged
npx husky install
npm pkg set scripts.prepare="husky install"
npx husky add .husky/pre-commit "npx lint-staged"
```

In a nutshell, these commands set up Husky and lint-staged for your project, ensuring that your code stays in tip-top shape.

## Formatting
Now, let's tackle code formatting. We've chosen [prettier](https://prettier.io/) as the default option, although [dprint](https://github.com/dprint/dprint) is also a viable alternative. Add the following lines to your `package.json`:

```json
{
  "scripts": {
    "format": "prettier . --write--ignore-unknown"
  },
  "lint-staged": {
    "**/*": "prettier --write --ignore-unknown"
  }
}
```

If you wish to configure Prettier further, you can create a `.prettierrc.js` file with your desired settings, and don't forget to add a `.prettierignore` file to exclude specific directories like `node_modules`.
- **.prettierrc.js**
```javascript
/** @type {import("prettier").Config} */
const config = {
    trailingComma: 'es5',
    tabWidth: 4,
    semi: false,
    singleQuote: true,
}
export default config
```
- **.prettierignore**
```
node_modules
```

## Linting

Let's move on to setting up [ESlint](https://eslint.org/) for your project. With ESLint, you have the flexibility to customize your linting rules according to your preferences. We recommend installing the following packages:
- [eslint-config-prettier](https://github.com/prettier/eslint-config-prettier) for not conflict between them
- [@typescript-eslint/eslint-plugin](https://github.com/typescript-eslint/typescript-eslint)
- [@typescript-eslint/parser](https://github.com/eslint/typescript-eslint-parser)

Here's how to configure ESLint in your package.json:
```json
{
  "scripts": {
    "lint": "eslint ./src --fix --max-warnings 0"
  },
  "lint-staged": {
    "**/*": "prettier --write --ignore-unknown",
    "**/*.ts": "eslint ./src --fix --max-warnings 0"
  }
}
```

To complete the setup, add `.eslintignore `and `.eslintrc.cjs` files. These files ensure that ESLint doesn't interfere with your project's essential directories and that it follows the rules you've defined.
- **.eslintignore**
```
node_modules
dist
```
- **.eslintrc.cjs**
```javascript
/* eslint-env node */
module.exports = {
    extends: [
        'eslint:recommended',
        'plugin:@typescript-eslint/recommended',
        'plugin:@typescript-eslint/eslint-recommended',
        'prettier',
    ],
    parser: '@typescript-eslint/parser',
    plugins: ['@typescript-eslint'],
    rules: {
        '@typescript-eslint/no-import-type-side-effects': 'error',
        '@typescript-eslint/consistent-type-imports': [
            'error',
            {
                fixStyle: 'inline-type-imports',
            },
        ],
    },
    root: true,
}
```

A special rule, that I have added is to handle the import type (more information on [my previous post](https://dev.to/faridz974/auto-import-with-type-48c8))

## Unit testing

Last but not least, let's talk about unit testing. Our recommended choice is [vitest](https://vitest.dev/), which has become increasingly popular lately. To integrate vitest into your project, simply run:

You can simply add the package

```bash
npm install -D vitest
```

Then create a simple configuration file `vitest.config.ts`

```typescript
/// <reference types="vitest" />
import { defineConfig } from 'vitest/config'

export default defineConfig({
    test: {
        coverage: {
            all: true,
            include: ['src'],
            reporter: ['html', 'json'],
            provider: 'v8',
        },
    },
})
```

## Visual Studio Code Integration



Do you love the convenience of IDE integration, where your code automatically gets polished as soon as you save your work? If you're using Visual Studio Code (VSCode), we've got some handy settings to supercharge your development experience. Just add the following lines to your `.vscode/settings.json` file:

```json
{
    "editor.codeActionsOnSave": {
        "source.fixAll": true,
        "source.sortMembers": true,
        "source.fixAll.eslint": true,
        "source.organizeImports": true
    },
    "editor.bracketPairColorization.enabled": true,
    "editor.defaultFormatter": "esbenp.prettier-vscode",
    "editor.formatOnSave": true,
    "editor.guides.bracketPairs": true,
    "typescript.tsdk": "node_modules/typescript/lib",
    "typescript.preferences.importModuleSpecifier": "relative",
    "workbench.tree.indent": 15,
    "workbench.tree.renderIndentGuides": "always",
    "workbench.colorCustomizations": {
        "tree.indentGuidesStroke": "#fc03ad"
    }
}

```

With this configuration in place, you're in for a treat:

- Eslint and code formatting will automatically work their magic as you save your files, ensuring that your code remains clean and error-free.
- Your imports will be sorted and organized neatly, making your codebase more maintainable.
VSCode will use the TypeScript version installed in your project's node_modules directory, eliminating version conflicts and ensuring consistency.
- The Bracket Pair Colorizeration will add a splash of color to your code by highlighting matching brackets. You can customize the colors to your heart's content.
- With workbench you can add grouping for your folders/files tree
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n3qjmco1qp8yrubavk3x.png)

These settings are designed to enhance your coding experience and keep your project in tip-top shape. So, unleash the full power of VSCode and watch your development workflow become even more efficient.




And that's it! With these steps, your Node project is equipped with essential tools for code formatting, linting, and unit testing. Enjoy the benefits of a well-structured and robust codebase. Happy coding! 🚀