TypeScript Linting and Formatting with ESLint + Prettier
TypeScript has become a popular choice for building large - scale JavaScript applications due to its static typing and enhanced developer experience. However, as projects grow, maintaining code quality and consistency becomes a challenge. This is where linting and formatting come into play. Linting helps in identifying potential errors, bad practices, and enforcing coding standards, while formatting ensures that the code has a consistent style. In this blog, we’ll explore how to use ESLint and Prettier together to lint and format TypeScript code effectively.
Table of Contents
- Fundamental Concepts
- Installation and Setup
- Usage Methods
- Common Practices
- Best Practices
- Conclusion
- References
Fundamental Concepts
Linting
Linting is the process of analyzing source code to flag programming errors, bugs, stylistic errors, and suspicious constructs. ESLint is a pluggable and configurable linting utility for JavaScript and TypeScript. It allows you to define rules that your code should adhere to, and it will then analyze your codebase and report any violations.
Formatting
Formatting refers to the process of arranging code in a consistent and readable way. Prettier is an opinionated code formatter that enforces a consistent style by parsing your code and re - printing it according to a set of rules. It can handle multiple programming languages, including TypeScript.
ESLint and Prettier Together
While ESLint can handle some basic formatting, its primary focus is on code quality and potential errors. Prettier, on the other hand, is solely focused on formatting. By using them together, we can get the best of both worlds: high - quality code with a consistent style.
Installation and Setup
1. Initialize a new project
If you haven’t already, create a new directory for your project and initialize it with npm:
mkdir typescript-project
cd typescript-project
npm init -y
2. Install TypeScript
npm install typescript --save - dev
Then, initialize a tsconfig.json file:
npx tsc --init
3. Install ESLint and related plugins
npm install eslint @typescript - eslint/parser @typescript - eslint/eslint - plugin --save - dev
@typescript - eslint/parseris used to parse TypeScript code.@typescript - eslint/eslint - pluginprovides a set of ESLint rules for TypeScript.
4. Initialize ESLint configuration
npx eslint --init
Follow the prompts to set up your ESLint configuration. You can choose options based on your project’s needs, such as using TypeScript and a specific style guide.
5. Install Prettier and related packages
npm install prettier eslint - plugin - prettier eslint - config - prettier --save - dev
eslint - plugin - prettierallows ESLint to run Prettier as an ESLint rule.eslint - config - prettierdisables ESLint rules that conflict with Prettier.
6. Configure ESLint to work with Prettier
In your .eslintrc file, add the following:
{
"extends": [
"eslint:recommended",
"plugin:@typescript - eslint/recommended",
"plugin:prettier/recommended"
],
"parser": "@typescript - eslint/parser",
"plugins": ["@typescript - eslint"],
"rules": {
// Add custom rules here if needed
}
}
7. Create a Prettier configuration file
Create a .prettierrc file in the root of your project:
{
"singleQuote": true,
"trailingComma": "es5",
"printWidth": 80
}
These are just some common configuration options. You can adjust them according to your preferences.
Usage Methods
Linting
To lint your TypeScript code, you can use the following command:
npx eslint src/**/*.ts
This will analyze all TypeScript files in the src directory and report any rule violations.
Formatting
To format your TypeScript code using Prettier, you can use the following command:
npx prettier --write src/**/*.ts
This will automatically format all TypeScript files in the src directory.
Combining Linting and Formatting
You can create an npm script in your package.json to run both linting and formatting together:
{
"scripts": {
"lint": "eslint src/**/*.ts",
"format": "prettier --write src/**/*.ts",
"lint - and - format": "npm run lint && npm run format"
}
}
Then, you can run npm run lint - and - format to perform both tasks.
Common Practices
Rule Configuration
- Use recommended rules: Start with the recommended rules provided by
@typescript - eslintand ESLint. These rules cover many common errors and best practices. - Customize rules: As your project evolves, you may need to customize rules to fit your specific requirements. For example, you can adjust the
max - line - lengthrule in ESLint or change Prettier’sprintWidthoption.
Ignoring Files
Create an .eslintignore and a .prettierignore file in the root of your project to exclude certain files or directories from linting and formatting. For example:
# .eslintignore
node_modules
dist
# .prettierignore
node_modules
dist
Integrating with IDEs
Most modern IDEs, such as Visual Studio Code, support ESLint and Prettier integrations. You can install the ESLint and Prettier extensions and configure them to automatically lint and format your code as you type.
Best Practices
Pre - commit Hooks
Use a tool like Husky to set up pre - commit hooks. This ensures that your code is linted and formatted before it is committed to the repository.
npm install husky --save - dev
npx husky install
npx husky add .husky/pre - commit "npm run lint - and - format"
Team Consistency
Ensure that all team members are using the same ESLint and Prettier configurations. This can be achieved by committing the .eslintrc and .prettierrc files to the repository.
Continuous Integration
Integrate linting and formatting checks into your CI/CD pipeline. For example, in a GitHub Actions workflow, you can add the following steps:
name: Lint and Format
on:
push:
branches:
- main
jobs:
lint - and - format:
runs - on: ubuntu - latest
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Set up Node.js
uses: actions/setup - node@v2
with:
node - version: '14'
- name: Install dependencies
run: npm install
- name: Lint and format
run: npm run lint - and - format
Conclusion
Linting and formatting your TypeScript code using ESLint and Prettier is essential for maintaining high - quality and consistent codebases. By understanding the fundamental concepts, setting up the tools correctly, and following common and best practices, you can significantly improve the development experience and reduce the number of bugs in your projects. Whether you are working on a small personal project or a large - scale enterprise application, integrating these tools into your workflow is a step in the right direction.
References
- [ESLint official documentation](https://eslint.org/docs/user - guide/getting - started)
- Prettier official documentation
- [@typescript - eslint official repository](https://github.com/typescript - eslint/typescript - eslint)
- Husky official repository
- GitHub Actions official documentation