ESLint vs Prettier: What’s the Difference and Why ESLint with Prettier is an Ideal Combination?

Quick Summary:

ESLint Prettier – two tools that play a pivotal role in building robust and scalable web apps by maintaining code quality. ESLint is a static code analysis tool used for identifying code issues and enforcing coding standards whereas Prettier is a code formatter focused on maintaining a consistent and visually appealing code style. Today we will focus on ‘ESLint vs Prettier’ comparison and find out whether they are competitors or complementariness that work together as an inseparable duo.

If you want a basic code formatter with lesser architectural and configuration complexity, you can go for Prettier. Use ESLint if you want to analyse static code for catching errors, enforcing coding standards and identifying potential issues in your codebase.

Use both ESLint Prettier together to leverage ESLint for static code analysis, enforcing coding standards and identifying codebase issues, while maintaining consistent code formatting with Prettier to get a comprehensive approach to code quality.

Core Differences: ESLint vs Prettier

ESLint and Prettier, are two essential tools in a developer’s toolkit, both serving distinctive and yet complementary purposes. Understanding the difference between ESLint and Prettier is crucial to understand why they work so well together. Their fundamental difference lies in their primary objective.  ESLint is primarily focused on identifying and reporting code quality issues, enforcing coding standards and catching potential bugs via static code analysis.

Prettier is focused on optimizing code formatting, aiming to deliver consistent and aesthetically appealing code styles. The synergy between ESLint and Prettier arise from their contrasting nature and objectives. By understanding and using their complementary services, you can improve your overall codebase quality significantly.

Today we are going to dive deeper into understanding the role of ESLint & Prettier in React coding, highlighting their unique features, configurations and how can be they be effectively used together in your current or next React project. We will also highlight the core differences between them so as to understand why they are compared so often and on what basis.

Chapter 1: What Is Eslint and Why is it Used?

ESLint is a linting JavaScript and JSX tool that is used by development teams to adhere to coding standards and following best practices.

What is ESLint?

ESLint analyses the code statically for finding out any potential style violations, errors and other such issues in the codebase, allowing developers to receive early feedback in their development process. It is popularly used for React projects as a preferred linting tool by many experienced React developers.

1.1 Key features and capabilities of ESLint

ESLint is a popular static code analysis tool for JavaScript. It has several key features like:

Key Features of ESLint Purpose
Error Catching Identifies and reports syntax errors and other potential issues in the code.
Configurability Highly configurable through different plugins, allows developers to take control and modify as per project needs.
Coding Standards Enforcement Enforces coding standards and best practices to ensure consistency and maintainability of codebase.
Extensibility Supports plugins and allows developers to extend ESLint’s functionality for addressing project specific requirements.
IDEs and Editors Seamless integrations with IDEs and Code Editors, with real-time feedback during coding
Automated Fixing Fixes certain type of issues automatically, reducing developers efforts for maintaining code consistency.
Plugin-based Ecosystem Boasts a rich ecosystem of plugins that cater to various frameworks and libraries with specific plugins for React, Vuejs and others.

1.2 How to install and configure ESLint?

ESLint can be extended with plugins to address specific requirements of a custom React project. By nature, ESLint is entirely pluggable. All of its rules are individual plugins and developers can add more during runtime.

For installing and configuring ESLint follow these basic steps:

  1. Create React App

If you haven’t already, create a React app using the following command.

npm create-react-app myreactapp
  1. Install ESLint

Install ESLint as a development dependency in your React project

npm install eslint –-save-dev
  1. Start setting up ESLint Configuration

To configure ESLint, run the following command:

npx eslint --init

Choose the options that are most suited for your project.

  1. Install ESLint Plugin for React

If you didn’t include ESLint React plugin in the ESLint initialization process, you should install it separately.

npm install eslint-plugin-react --save-dev

You will have to add ‘react’ to the plugins section of your ‘eslintrc.js’ file.

  1. Configuring ESLint for React

Open your ‘eslintrc.js’ file and configure it for your React project. A basic configuration example can look like this:

module.exports = {
  // ... other configurations
  plugins: ['react'],
  extends: [
    // ... other extends
    'plugin:react/recommended',
  ],
  // ... other rules
};
  1. Add Accessibility by installing ESLint for JSX-A11y (Optional)

If you are considering addressing accessibility considerations for your app, this plugin can come handy:

npm install eslint-plugin-jsx-a11y --save-dev
  1. Run ESLint on React

You can run ESLint on your React project by using the following command:

npx eslint

This analyses your project files and reports any linting warnings or errors.

1.3 Overview of ESLint Plugins and Extensibility

If configured and customized properly, ESLint can be the best asset in a developer’s arsenal. ESLint provides various plugins and extensibility support to enhance its capabilities to adapt to various project environments and requirements.  More than pre-configured ESLint plugins, developers can also create their custom rules and use it for their specific projects or make it available to the community at large using Git or other such repositories.

1.4 How to extend ESLint with Custom Rules?

ESLint allows developers to add custom rules to configure ESLint as per their project. Why is it important? Because the core ESLint rules may not have your specific configuration or sharable configs. For instance, when using a frontend framework like React or a framework such as Vue, you would need to add custom rules to enforce best practices that align to that particular framework.

Step by step guide to adding custom rules to your ESLint configuration:

  1. Create a new directory for holding your custom rules
  2. Create a new file inside this new directory for each rule you wish to create
  3. Export an object to the files that defines their rules
  4. Add the following script to the ‘package.json’ file of your custom rules directory:
"scripts": {
 	 "test": "jest",
	},
  1. Run ‘npm install’ for installing Jest to test your rules.
  2. Write test cases for the custom rules with Jest.
  3. Run ‘npm run test’ to execute your tests. On success, you should see all your tests passing.
  4. Update this ESLint configuration and include it in your custom rules.

Examples of popular ESLint plugins for React

Popular ESLint Plugin Purpose
eslint-plugin-react Includes rules specifically for React projects like enforcing consistent usage of React component lifecycle methods.
eslint-plugin-jsx-a11y Includes rules for improving accessibility of JSX elements like ensuring all interactive elements have their proper ARIA attributes.
eslint-plugin-react-hooks This plugin is meant to leverage React Hooks while providing rules for its proper usage like ensuring hooks remain inside the functional components and all their dependencies are correctly defined.
eslint-plugin-prettier Yes, ESLint comes with a plugin for extending Prettier code formatting into ESLint which allows developers to ensure even spacing, indentation and proper line breaks across the codebase.

Amplify Your In-House Expertise with
Aglowid’s Seasoned ReactJS Specialists

Hire ReactJS Developers

Chapter 2: What is Prettier Used For?

Prettier is an opinionated code formatter which supports various programming languages such as JSON, JavaScript, JSX, Markdown and even CSS.

What is Prettier?

It has gained massive popularity amongst developers as the go-to code formatter that allows developers for formatting their code quickly and consistently across large codebases. The main purpose of Prettier is to eliminate inconsistent styling, whitespace changes and other commonly found coding style issues.

2.1 What is a code formatter and why is it important?

A code formatter is the visual layout and styling of a codebase to ensure its in a presentable state and is consistent to the style guides which eases collaborating and working on complex codebases.

Good formatting is important because:

  • It helps the code be more readable and maintainable
  • Avoids interruptions and arguments on style changes
  • Allows developers to scan through the code faster
  • Automatic formatting saves manual formatting effort

2.2 Key Features of Prettier

Prettier is a popular code formatter that has many key features such as:

Prettier Key Features Purpose
Consistent Code Formatting Enforces consistent coding style across the project to eliminate arguments over formatting preferences.
Language Agnostic Support for multiple programming languages, making it ideal for full-stack development projects.
Automatic Code Formatting Automatically formats code, reducing the need of manual formatting.
Configurability Offers decent configurability through the ‘.prettierrc’ configuration file.
Preservation of Code Intent Prettify ensures the code intent of developer isn’t affected by avoiding making unnecessary changes to the logical structure of the code.
Ease of Adoption Can be added to existing projects without heavy configuration requirements.
IDEs and Editors Seamless integrations with popular IDEs and Code Editors with on-the-fly code formatting when writing the code.
Team Code Consistency Facilitates consistent code performance by following top React Performance Optimization tips and styling across global teams with its opinionated approach.

2.2 How do I set up Prettier?

Setting up Prettier in React projects requires you to follow a few straightforward steps. Let’s begin:

  1. Start by Installing Prettier

Install prettier as a development dependency in your project using NPM or Yarn. Open your terminal and run the following command:

# Using npm
npm install --save-dev prettier
 
# Using yarn
yarn add --dev prettier
  1. Create a configuration file (optional)

Prettier is good to go with default settings, however, if you do wish to create a configuration file, you can do so in your project’s roots for customizing a few options. For instance:

// .prettierrc
{
  "semi": false,
  "singleQuote": true,
  "printWidth": 60,
  "tabWidth": 2
}

This configuration tells Prettier to use single quotes with print width to 60 characters and add a tab with 2 spaces of width.

  1. Add Scripts to ‘package.json’ (optional)

You can add scripts to the ‘package.json’ file for simplifying Prettier implementation. For instance:

// package.json
{
  "scripts": {
    "format": "prettier --write \"src/**/*.js\""
  }
}

Using this script will format all JavaScript files under the ‘src’ directory.

2.3 Integrate with your Code Editor

Most code editors come with extension for Prettier, hence all you need to do is install Prettier for your preferred editor and enable automatic formatting on save.

2.4 Run Prettier on React

You can now run Prettier on React by simply using the command line or the npm script:

# Using npx
npx prettier --write "src/**/*.js"
 
# Using npm script
npm run format
 
# Using yarn script
yarn format

Following these steps, you will be able to set up Prettier for your React app, enhancing code formatting, consistency and readability.

Prettier with Linters – Why, and How to Integrate Prettier and ESLinter with React?

Integrating Prettier with Linters like ESLint is a best practice in modern React development workflows. You need to understand the why, how and the need for combining Prettier with Linters.

Why should I use Prettier with ESLint?

Prettier is a dedicated code formatter with a single purpose to ensure code styling consistency across your codebase. Combining Prettier with ESLint or any other linter will help you not only keep your code properly formatted but also improve your code quality, resulting in a richer codebase. Moreover, automated formatting and linting processes reduce the developers’ need for manual effort significantly, allowing them to focus more on refining the logic of the app.

Why should I use Prettier with ESLint

Get both – Code Formatting and Code Quality

Prettier takes care of code formatting, ensuring your codebase looks aesthetically pleasing and remains consistent throughout. It automatically formats your codebase as per predefined rules and conventions. ESLint focuses on code quality and helps identify potential issues, enforce coding standards and catch errors and bugs early.

Reduce manual work with Automated Formatting

Prettier can automatically format your codebase, saving developers from several hours of manually fixing formatting issues. It also eliminates chances of inconsistency. ESLint also has formatting rules and attempts to solve minor codebase problems automatically, saving developers time to focus on more important problems.

Improved Collaboration

One of the biggest challenges of working in teams comes from inconsistent coding practices and poor testing practices. ESLint provides real-time feedback during development, allowing global teams to detect errors and bugs while coding, allowing them to resolve it at its nascent stage, keeping the codebase intact. Prettier enforces certain coding styles and rules, which takes away the challenges that come with inconsistent code styling. Hence using ESLint with Prettier allows developers to focus on writing the code rather than discussing the code formatting style or conducting tedious code reviews.

How to add ESLint and Prettier to React Project?

Now the important question, how to integrate ESLint with Prettier for your React project. Since we have already covered how to install Prettier and ESLint and Prettier separately above, we will directly focus on how to seamlessly integrate them for your improving your codebase quality and formatting:

  1. If you already have a React project, you can skip this step. Otherwise, you can create your React app using any preferred method.

Let’s use the create-react-app for our example.

npx create-react-app my-react-app
cd my-react-app
  1. Next, we will install all dependencies – ESLint and Prettier with a few additional packages that will help form a synergy between them allowing them to work together.
# Installing ESLint and its configuration
npm install eslint --save-dev
npx eslint --init
 
# Installing Prettier and its configuration
npm install --save-dev prettier eslint-config-prettier eslint-plugin-prettier
  1. Now we can add rules for Prettify and React in the ‘.eslintrc.js’ file.
module.exports = {
  // ... other configurations ...
  extends: [
    'react-app',
    'plugin:prettier/recommended', // Use eslint-config-prettier to disable ESLint formatting rules
  ],
  rules: {
    // ... other rules ...
    // Additional rules for React
    'react/jsx-filename-extension': [1, { extensions: ['.js', '.jsx'] }],
    'react/jsx-props-no-spreading': 'off', // Enable if needed
  },
};
  1. Next, we will set up Prettier by creating a ‘.prettierrc’ file for configuring Prettier options:
{
  "singleQuote": true,
  "semi": false,
  "tabWidth": 2,
  "trailingComma": "all"
}
  1. After we configure ESLint and Prettier, we will create scripts for both and add it to the ‘package.json’ file to run them.
"scripts": {
  "lint": "eslint .",
  "lint:fix": "eslint --fix .",
  "format": "prettier --write ."
}
  1. Next, let’s talk about enhancing your development experience with some must-have VS Code extensions for frontend developers. If you prefer using VSCode for your React projects, integrating ESLint and Prettier can be a game-changer. Although this is optional and only applicable if you preffer VSCode for running and managing your React projects. However, it is ideal if you want to enable automatic formatting on save. Just install the VS Code ESLint Extension and Prettier – Code formatter extension. After which, you need to add following settings to your VS Code settings which you can find in the ‘settings.json’ file.
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.codeActionsOnSave": {
  "source.fixAll.eslint": true
},
  1. Now you will be able to run ESLint and Prettier by running the defined scripts:
npm run lint
npm run lint:fix
npm run format

The first script will check the codebase for linting errors whereas the ‘lint:fix’ script will attempt to fix them and ‘format’ will apply the Prettify formatting.

Now you are good to go with consistent code style and ease of finding potential issues in your React project as per your ESLint and Prettier configurations.

Wrapping Up!

Using ESLint with Prettier is a great option for all JavaScript projects. It enables developers to focus more on writing robust code while focusing on business logic by automatically managing the formatting and basic bug fixes and identification tasks, while enforcing coding styles and conventions which enables better collaboration and reduces chance of coding errors.

Cutting Costs but
NOT Cutting Quality

that’s how we roll! 🚀

Hire Web Developers

FAQs

ESLint and Prettier are two drivers towards the same goal. ESLint is a linter tool which focuses on identifying and fixing problems in your JavaScript code by enforcing coding standards. It helps catch syntax errors, style issues and potential bugs. Prettier on the other hand is a code formatter that formats your code for consistent styling. It does not catch errors or enforce any coding standards like ESLint.

ESLint can be used without Prettier, since both of their purpose are significantly different. ESLint is a linting tool that focuses on optimizing code standards, analyzing codebase for potential bugs and catching syntax errors. Hence it is not dependent on Prettier to carry out its tasks, however most developers suggest using both the tools together to get error-free codebase with ESLint and perfectly formatted and readable codebase with Prettier.

Prettier is a code formatter and not a linter. It automatically formats your code to maintain consistent styling as per set of predefined set of rules for ensuring consistent and readable styling throughout the codebase. It does not carry out any role of a linter as it does not provide any services to identify codebase bugs, following best practices or maintaining code quality.
Need Consultation?

Put down your query here...

    Saurabh Barot, CTO at Aglowid IT Solutions, brings over a decade of expertise in web, mobile, data engineering, Salesforce, and cloud computing. Known for his strategic leadership, he drives technology initiatives, oversees data infrastructure, and leads cross-functional teams. His expertise spans across Big Data, ETL processes, CRM systems, and cloud infrastructure, ensuring alignment with business goals and keeping the company at the forefront of innovation.

    Related Posts