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
If Git is not initialized yet, run the following command:
git init
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
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,
);
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
Next, create a Prettier config file called .prettierrc. Here's the recommended config:
{
"singleQuote": true
}
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
Next, run the following commands to set up Husky:
npx husky init
echo "lint-staged" > .husky/pre-commit
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"
}
}
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)