DEV Community

Ibrahim
Ibrahim

Posted on

How to Set Up ESLint, Prettier, Husky, and Lint-Staged in a TypeScript Project

I usually begin a Typescript project by first setting up ESLint, Prettier, Husky, and Lint-Staged.

ESLint and Prettier help keep the code clean and consistent with the defined standards.

Husky and Lint-Staged used to automatically run ESLint and Prettier before a git commit.

Follow these steps to set up all the tools:

1. Set Up Git

First, make sure Git is initialized in the project by running:

git status
# On branch master
# nothing to commit, working tree clean
Enter fullscreen mode Exit fullscreen mode

If Git is not initialized yet, run the following command:

git init
Enter fullscreen mode Exit fullscreen mode

2. Set Up Eslint

ESLint is a tool used to analyze and fix issues in TypeScript code.

Here's how to install ESLint and the TypeScript plugin:

npm install --save-dev eslint @eslint/js typescript-eslint
Enter fullscreen mode Exit fullscreen mode

Next, create an ESLint config file called eslint.config.mjs. Here's the recommended config:

// @ts-check

import eslint from '@eslint/js';
import tseslint from 'typescript-eslint';

export default tseslint.config(
  eslint.configs.recommended,
  tseslint.configs.recommended,
);
Enter fullscreen mode Exit fullscreen mode

For more configuration options, visit: https://typescript-eslint.io/rules/.

3. Set Up Prettier

Prettier is a tool used to format TypeScript code to make it cleaner and more consistent.

Here's how to install Prettier:

npm install --save-dev --save-exact prettier
Enter fullscreen mode Exit fullscreen mode

Next, create a Prettier config file called .prettierrc. Here's the recommended config:

{
  "singleQuote": true
}
Enter fullscreen mode Exit fullscreen mode

For more configuration options, visit: https://prettier.io/docs/options.

4. Set Up Husky and Lint-Staged

Husky is a tool used to run specific scripts on Git hooks.

Lint-Staged is a tool used to run commands like ESLint and Prettier on staged files before they are commited.

Here's how to install Husky and Lint-Staged:

npm install --save-dev husky lint-staged
Enter fullscreen mode Exit fullscreen mode

Next, run the following commands to set up Husky:

npx husky init
echo "lint-staged" > .husky/pre-commit
Enter fullscreen mode Exit fullscreen mode

Next, open the package.json file and add a lint-staged section with commands to run on staged files.

{
  "lint-staged": {
    "*.{ts,js,css,md}": "prettier --write",
    "*.{ts,js}": "eslint --cache --fix"
  }
}
Enter fullscreen mode Exit fullscreen mode

Once the setup is complete, Husky will automatically run the scripts specified in lint-staged like ESLint and Prettier before any commit is made.

Top comments (0)