ESLint and Prettier: A Guide to Cleaner Code
Tags: javascript, react, webdev, beginners
Published: 2024-07-01 14:51:19

## ESLint

ESLint is a tool that helps find and fix problems in JavaScript/TypeScript code. Using ESLint can help you write better and consistent code, which is especially useful when working in a team.

> **What is Lint?** Linting is when a tool analyzes your code to find errors and style issues.

***

### ESLint Example

- Example 1 : Keeping consistent code style (quotes, indentation, semicolons, etc.)

```jsx
const obj = {
  firstname: "Joy", // Error : for using double quotes
  lastname: "Lee",
}
```

- Example 2 : Catching syntax errors

```jsx
const x = 10
x = 5 // Error: const variable can't be reassigned
```

- Example 3 : Warning for unused variables

```jsx
function add(a, b) {
  const result = a + b // warning: 'result' is assigned but never used
  return a + b
}
```

- Example 4 : Optimizing code

```jsx
if (isAvailable === true) {..} // ❌
if (isAvailable) {..} // ⭕️
```

- Example 5: Checking React prop-types

```jsx
// Warning: 'name' prop is not specified
export const MyComponent = ({ name }) => {
  return <div>Hello, {name}</div>
}
```

***

### Installing ESLint

```bash
npm init @eslint/config
```

To run ESLint, add the following to the scripts section in `package.json`, then run `npm run lint` in the terminal.

```json
"scripts": {
  // ...
  "lint": "eslint .",
  "lint:fix": "eslint --fix ."
}
```

***

### ESLint Config File

You can configure ESLint rules using a config file. Until ESLint version 7, `.eslintrc` was used for config, but from version 8, you use `eslint.config.js`
<br/> (reference : https://github.com/jsx-eslint/eslint-plugin-react#configuration)

```jsx
// eslint.config.mjs
import globals from "globals"
import pluginJs from "@eslint/js"
import tseslint from "typescript-eslint"
import pluginReactConfig from "eslint-plugin-react/configs/recommended.js"
import { fixupConfigRules } from "@eslint/compat"

export default [
  // Apply settings to all JavaScript, TypeScript, and JSX/TSX files
  { files: ["**/*.{js,mjs,cjs,ts,jsx,tsx}"] },
  {
    languageOptions: {
      parserOptions: {
        // Set parser options for parsing JSX
        ecmaFeatures: { jsx: true },
        ecmaVersion: 2021,
        sourceType: "module",
      },
      globals: globals.browser, // Add browser global variables
    },
  },

  pluginJs.configs.recommended, // Apply basic ESLint rules
  ...tseslint.configs.recommended, // Apply TypeScript rules
  ...fixupConfigRules(pluginReactConfig), // Apply React rules

  {
    settings: {
      // Automatically detect React version
      react: { version: "detect" },
    },
  },
  {
    // Additional custom rules
    rules: {
      "no-console": "warn", // Warn when using console.log
      "no-unused-vars": "warn", // Warn for unused variables
      "react/prop-types": "off", // Disable React prop-types
      "@typescript-eslint/no-unused-vars": ["warn"],
      // Warn for unused TypeScript variables
    },
  },
]
```

***
***

## Prettier

Prettier is a tool that formats your code according to a set style. It is often used with ESLint to fix errors and improve code quality, and Prettier to automatically format the code for readability and consistency.

### Installing Prettier

```bash
npm i prettier --save-dev
```

***

### Prettier Config

Create a `.prettierrc` file and add the following rules:

```json
{
  "singleQuote": true,
  "semi": false,
  "tabWidth": 2,
  "printWidth": 80,
  "endOfLine": "auto"
}
```

***

## Combining ESLint and Prettier

### Differences Between ESLint and Prettier

- **ESLint**: Mainly used to improve code quality and prevent errors. It checks for syntax errors, potential bugs, and style issues.

- **Prettier**: Automatically formats code according to style rules like indentation, spaces, and quotes.

***

### Preventing ESLint and Prettier Conflicts

ESLint and Prettier can have conflicting rules about style. To prevent this, add the following plugins:

1. `eslint-config-prettier`: Adds Prettier as an ESLint plugin. It makes Prettier errors show up as ESLint errors.

2. `eslint-plugin-prettier`: Disables ESLint rules that conflict with Prettier.

- Installing Plugins

```bash
npm i -D eslint-config-prettier eslint-plugin-prettier @types/eslint-config-prettier
```

***

### Adding Prettier to ESLint Config

Add Prettier settings to `eslint.config.js`. Make sure Prettier rules are at the end !

```js
// eslint.config.mjs
import globals from "globals"
import pluginJs from "@eslint/js"
import tseslint from "typescript-eslint"
import pluginReactConfig from "eslint-plugin-react/configs/recommended.js"
import { fixupConfigRules } from "@eslint/compat"

// 👋 Import prettier plugins
import prettierConfig from "eslint-config-prettier" 
import pluginPrettier from "eslint-plugin-prettier"


export default [
  { files: ["**/*.{js,mjs,cjs,ts,jsx,tsx}"] },
  {
    languageOptions: {
      parserOptions: {
        ecmaFeatures: { jsx: true },
        ecmaVersion: 2021,
        sourceType: "module",
      },
      globals: globals.browser,
    },
  },

  pluginJs.configs.recommended,
  ...tseslint.configs.recommended, 
  ...fixupConfigRules(pluginReactConfig),

  {
    plugins: {
      prettier: pluginPrettier, // 👋 Add prettier plugin
    },
  },
  {
    settings: {
      react: { version: "detect" },
    },
  },
  {
    // Additional custom rules
    rules: {
      "no-console": "warn", 
      "no-unused-vars": "warn", 
      "react/prop-types": "off",
      "@typescript-eslint/no-unused-vars": ["warn"],

      // 👋 Add prettier rules at the bottom
      ...prettierConfig.rules, // Merge Prettier and ESLint rules
      "prettier/prettier": "error", // Show Prettier errors as ESLint errors
    },
  },
]
```

***

### Setting Up VSCode Formatter

1. Install 'Prettier - Code formatter' extension in VSCode.

2. Go to VSCode settings, search for 'Default Formatter,' and select 'Prettier - Code formatter.'
<img width="680" alt="" src="https://github.com/devjoylee/toyota_display_ads/assets/68415905/b0dd6dc9-88d0-4afd-855d-24b49bc4ab08">

3. Search for `formatOnSave` in VSCode settings and check the box. This ensures Prettier formats your code every time you **save a file.**
<img width="680" alt="" src="https://github.com/devjoylee/toyota_display_ads/assets/68415905/896c76da-99bb-454d-81d0-61e13a5c0aac">

***

## Conclusion

Using ESLint and Prettier together can improve the quality and readability of your code. ESLint helps catch errors and enforce code quality, while Prettier ensures your code is consistently formatted. Setting them up is easy and can save you a lot of time and hassle in the long run. 

Happy coding!