Blog>
Snippets

Integrating Prettier with ESLint

Demonstrate the integration of Prettier with ESLint to format code and fix style issues based on ESLint rules.
// Step 1: Install the required packages
npm install eslint prettier eslint-plugin-prettier eslint-config-prettier --save-dev
Install ESLint, Prettier and the necessary plugins that allow them to work together.
// Step 2: Create or update your .eslintrc.js with the following configuration
module.exports = {
  // Extend `eslint:recommended` and the `prettier` configuration
  extends: [
    'eslint:recommended',
    'plugin:prettier/recommended'
  ],
  // Define the parser options
  parserOptions: {
    ecmaVersion: 2020, // Recommended to set the version of ECMAScript syntax you want to use
    sourceType: 'module' // Set to use ECMAScript modules feature
  },
  // Enable ESLint rules and Prettier rules
  rules: {
    // Example of overriding a rule
    'prettier/prettier': 'error',
    // Add custom ESLint rules or override Prettier-integrated ones here
    // 'no-unused-vars': 'warn',
    // 'eqeqeq': 'error',
    // ... more rules
  },
  // Define global variables that are predefined
  globals: {
    // 'Promise': 'readonly',
    // ... more globals
  }
};
Configure ESLint with Prettier in a '.eslintrc.js' file. Add the 'plugin:prettier/recommended' configuration to enable Prettier as a plugin.
// Step 3: Add a .prettierrc file (optional) to configure Prettier format options
{
  "singleQuote": true,
  "trailingComma": "es5",
  "bracketSpacing": true,
  "semi": false
}
Optionally create a '.prettierrc' file to customize Prettier format options.
// Step 4: Add a lint script to your package.json
"scripts": {
  "lint": "eslint . --fix"
}
Add a script in your 'package.json' to run ESLint with the --fix flag to automatically fix issues.
// Usage example:
// Filename: calculate.js
function calculate(x, y) {
  const sum = x + y;
  return sum; // This line will be formatted according to ESLint and Prettier rules
}

// Run the lint command
// $ npm run lint
An example usage of the configured setup to demonstrate linting and formatting a JavaScript file according to the rules.