乐闻世界logo
搜索文章和话题

How do I set up Prettier with Airbnb JavaScript Style Guide

1个答案

1

When it comes to code formatting tools, Prettier is a widely adopted choice because it automatically formats code to enhance consistency and readability. Integrating Prettier with the Airbnb JavaScript Style Guide further improves code quality and team collaboration. Below, I'll walk you through the steps to implement this integration:

1. Install Required Packages

First, ensure your project has Node.js and npm set up. Then, in your project root directory, install Prettier and the Airbnb ESLint configuration packages, as Prettier integrates with ESLint to maintain style consistency:

bash
npm install --save-dev prettier eslint-config-prettier eslint-plugin-prettier eslint-config-airbnb eslint-plugin-import eslint-plugin-react eslint-plugin-jsx-a11y eslint-plugin-react-hooks

Here, eslint-config-prettier and eslint-plugin-prettier are packages that disable unnecessary or potentially conflicting ESLint rules. Meanwhile, eslint-config-airbnb contains the Airbnb JavaScript Style Guide.

2. Configure ESLint

In your project root directory, create or modify the .eslintrc file (or add an eslintConfig section in package.json) to include Airbnb and Prettier configurations:

json
{ "extends": ["airbnb", "plugin:prettier/recommended"], "rules": { "react/jsx-filename-extension": [1, { "extensions": [".js", ".jsx"] }], "prettier/prettier": ["error", {}, { "usePrettierrc": true }] } }

Here, the "plugin:prettier/recommended" in the extends property enables seamless integration between Prettier and ESLint, activating eslint-plugin-prettier and eslint-config-prettier.

3. Create Prettier Configuration File

In your project root directory, create a .prettierrc file to define your formatting rules. For example:

json
{ "printWidth": 100, "singleQuote": true, "trailingComma": "es5" }

This configuration specifies using single quotes, adding trailing commas where applicable, and limiting line length to 100 characters.

4. Integrate into Editor

To boost development efficiency, integrate Prettier into your preferred code editor (e.g., VSCode or Sublime Text) for automatic formatting on save. For VSCode, install the Prettier extension and enable formatting on save via settings:

json
{ "editor.formatOnSave": true, "javascript.validate.enable": false, "[javascript]": { "editor.formatOnSave": true }, "prettier.disableLanguages": [] }

5. Run and Test

Finally, run ESLint to verify compliance with the Airbnb Style Guide and Prettier formatting:

bash
npx eslint --fix .

This command automatically fixes fixable formatting issues and reports remaining violations.

Summary

Using the Airbnb JavaScript Style Guide with Prettier not only ensures consistent code style but also enhances readability and maintainability. By following these steps, you can easily implement this in your project. I hope this helps with your coding workflow!

2024年7月25日 23:24 回复

你的答案