Setting Up Your React Project with TypeScript, ESLint, Prettier, Jest, and Husky
Set Up React with TypeScript, ESLint, Prettier, Jest & Husky
Intoduction
This guide will walk you through configuring a React project using TypeScript, ESLint, Prettier, Jest, and Husky. These tools help maintain code quality, enforce consistent styling, run tests, and automate workflows. By the end of this guide, you’ll have a robust development environment that automates linting, formatting, and testing before committing code.
Project Overview
This setup uses the following tools:
- TypeScript: Ensures type safety and better code structuring.
- ESLint: Ensures consistent coding practices and identifies potential issues early.
- Prettier: Automatically formats code for consistency.
- Jest: Testing framework for running unit tests and checking code coverage.
- Husky: Automates pre-commit hooks to ensure code quality before submission.
Step 1: ESLint Configuration
ESLint is a tool for identifying and reporting on patterns found in JavaScript/TypeScript code. It helps ensure your code adheres to a specific style guide and avoids common errors.
ESLint Configuration (.eslintrc.json):
{ "env": { "browser": true, "es2021": true, "jest": true }, "parser": "@typescript-eslint/parser", "parserOptions": { "project": "./tsconfig.json", "tsconfigRootDir": "./", "sourceType": "module" }, "extends": [ "airbnb", "airbnb-typescript", "eslint:recommended", "plugin:@typescript-eslint/recommended", "plugin:prettier/recommended", "react-app", "react-app/jest" ], "plugins": ["import", "react", "@typescript-eslint", "prettier"], "rules": { "react/function-component-definition": "off", "import/no-extraneous-dependencies": [ "error", { "devDependencies": true } ], "@typescript-eslint/no-explicit-any": "off", "@typescript-eslint/no-unused-vars": "error" } }
Explanation:
- Parser: We use @typescript-eslint/parser to parse TypeScript code.
- Extends: This configuration extends Airbnb’s style guide for React and TypeScript, along with recommended rules for ESLint and Prettier.
- Rules: Some custom rules are applied, such as:
- Turning off the no-explicit-any rule for flexibility.
- Enforcing the rule that unused variables will trigger errors.
- Allowing devDependencies to be used.
Key Benefits:
- Catches potential bugs early.
- Enforces consistent coding style.
- Integrates well with TypeScript.
Step 2: Prettier Setup
Prettier is an opinionated code formatter that ensures your code is always styled the same way, regardless of the IDE or editor used.
Prettier Configuration (.prettierrc):
{ "tabWidth": 2, "printWidth": 80, "semi": false, "trailingComma": "none", "singleQuote": true, "endOfLine": "lf", "overrides": [ { "files": "*.scss", "options": { "parser": "scss" } } ] }
Explanation:
- tabWidth: Uses 2 spaces for indentation.
- printWidth: Limits lines to 80 characters.
- semi: Disables semicolons at the end of statements.
- singleQuote: Enforces single quotes instead of double quotes.
- End of Line: Uses line-feed (LF) for line breaks.
Key Benefits:
- Automated code formatting ensures that code style remains consistent across your project.
- Integrates with ESLint to streamline the development process.
Step 3: Jest for Testing and Coverage
Jest is a robust testing framework used for testing JavaScript and TypeScript applications. It provides out-of-the-box support for running tests and measuring code coverage.
Example Jest Configuration in package.json:
"jest": { "transformIgnorePatterns": [ "/node_modules/(?!axios)/" ] }
To generate a code coverage report, run:
npm run test — –coverage
Step 4: Automating with Husky and Lint-Staged
To prevent committing code that doesn’t pass linting or formatting checks, we use Husky to set up Git hooks and Lint-staged to run these checks only on staged files.
Husky and Lint-Staged Setup in package.json:
"lint-staged": { "src/**/*.{js,jsx,ts,tsx}": "npm run lint-fix", "src/**/*.{js,jsx,ts,tsx,scss,json,md}": [ "prettier --cache --write" ] }
Explanation:
- Husky sets up pre-commit hooks, so every time a commit is made, it runs the specified linting and formatting tasks.
- Lint-staged ensures that only staged files are linted and formatted, improving efficiency.
Key Benefits:
- Prevents committing badly formatted or linted code.
- Automates code quality checks during the commit process.
Step 5: Adding Custom NPM Scripts
Custom scripts make it easier to perform repetitive tasks such as linting, testing, and formatting. Here’s a list of useful npm scripts for this project:
NPM Scripts in package.json:
"scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject", "lint": "eslint . --max-warnings=0", "lint-fix": "eslint --fix . --max-warnings=0", "prepare": "husky install", "format": "prettier ./src --write" }
Explanation:
- start: Starts the React development server.
- build: Builds the React app for production.
- test: Runs the test suite using Jest.
- eject: Ejects the create-react-app configuration for full control.
- lint: Runs ESLint and ensures no warnings.
- lint-fix: Automatically fixes linting issues.
- prepare: Installs Husky hooks.
- format: Formats all source files using Prettier.
Step 6: TypeScript Configuration
Here’s a basic tsconfig.json configuration to ensure smooth TypeScript development in your React project:
{ "compilerOptions": { "target": "ES2021", "lib": [ "dom", "dom.iterable", "esnext" ], "allowJs": true, "skipLibCheck": true, "esModuleInterop": true, "strict": true, "forceConsistentCasingInFileNames": true, "noFallthroughCasesInSwitch": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react-jsx", "baseUrl": "src" }, "include": [ "src", "./setupTests.ts" ] }
Key Configuration Options:
- strict: Ensures strict type checking.
- jsx: Supports React’s JSX syntax.
- baseUrl: Helps with relative imports by setting the base directory to src.
Conclusion
By integrating ESLint, Prettier, Jest, and Husky, this setup ensures that your code is clean, well-formatted, and thoroughly tested before every commit. Here’s a quick recap of the main benefits:
- ESLint: Catches errors and enforces consistent coding standards, improving code quality and reducing the likelihood of bugs.
- Prettier: Automates code formatting, ensuring a unified style across the codebase, which enhances readability and maintainability.
- Jest: Facilitates writing robust unit tests and monitoring code coverage, ensuring that your code functions as expected and remains reliable.
- Husky: Automates pre-commit checks, running linting and formatting scripts to ensure that only well-formatted and lint-free code is committed to the repository.
This integrated approach not only enhances the quality and consistency of your code but also streamlines your development workflow, making the process of coding, testing, and maintaining your project more efficient and effective. By adopting these practices, you set a strong foundation for a scalable and maintainable codebase.