DEV Community

Joy Lee🌻
Joy Lee🌻

Posted on

ESLint and Prettier: A Guide to Cleaner Code

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.)
const obj = {
  firstname: "Joy", // Error : for using double quotes
  lastname: "Lee",
}
Enter fullscreen mode Exit fullscreen mode
  • Example 2 : Catching syntax errors
const x = 10
x = 5 // Error: const variable can't be reassigned
Enter fullscreen mode Exit fullscreen mode
  • Example 3 : Warning for unused variables
function add(a, b) {
  const result = a + b // warning: 'result' is assigned but never used
  return a + b
}
Enter fullscreen mode Exit fullscreen mode
  • Example 4 : Optimizing code
if (isAvailable === true) {..} // ❌
if (isAvailable) {..} // ⭕️
Enter fullscreen mode Exit fullscreen mode
  • Example 5: Checking React prop-types
// Warning: 'name' prop is not specified
export const MyComponent = ({ name }) => {
  return <div>Hello, {name}</div>
}
Enter fullscreen mode Exit fullscreen mode

Installing ESLint

npm init @eslint/config
Enter fullscreen mode Exit fullscreen mode

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

"scripts": {
  // ...
  "lint": "eslint .",
  "lint:fix": "eslint --fix ."
}
Enter fullscreen mode Exit fullscreen mode

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

(reference : https://github.com/jsx-eslint/eslint-plugin-react#configuration)

// 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
    },
  },
]
Enter fullscreen mode Exit fullscreen mode


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

npm i prettier --save-dev
Enter fullscreen mode Exit fullscreen mode

Prettier Config

Create a .prettierrc file and add the following rules:

{
  "singleQuote": true,
  "semi": false,
  "tabWidth": 2,
  "printWidth": 80,
  "endOfLine": "auto"
}
Enter fullscreen mode Exit fullscreen mode

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
npm i -D eslint-config-prettier eslint-plugin-prettier @types/eslint-config-prettier
Enter fullscreen mode Exit fullscreen mode

Adding Prettier to ESLint Config

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

// 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
    },
  },
]
Enter fullscreen mode Exit fullscreen mode

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.'

  3. Search for formatOnSave in VSCode settings and check the box. This ensures Prettier formats your code every time you save a file.


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!

Top comments (1)

Collapse
 
raajaryan profile image
Deepak Kumar

Hello everyone,

I hope you're all doing well. I recently launched an open-source project called the Ultimate JavaScript Project, and I'd love your support. Please check it out and give it a star on GitHub: Ultimate JavaScript Project. Your support would mean a lot to me and greatly help in the project's growth.

Thank you!