📜  react eslint prettier - Javascript (1)

📅  最后修改于: 2023-12-03 15:19:43.121000             🧑  作者: Mango

React, ESLint, and Prettier

As a developer, you're probably familiar with React - a popular JavaScript library used for building user interfaces. However, as your applications grow, it becomes difficult to maintain consistent code styles across your team. That's where ESLint and Prettier come in.

What is ESLint?

ESLint is a pluggable and configurable JavaScript linter that helps identify and enforce best practices in your codebase. It can be customized to suit your needs, and you can define your own rules or use the existing ones.

Here's an example of a custom ESLint rule that enforces the use of semicolons at the end of each statement:

// .eslintrc.js

module.exports = {
  rules: {
    'semi': ['error', 'always']
  }
};
What is Prettier?

Prettier is a code formatter that helps maintain a consistent code style in your project. It automatically formats your code based on a set of predefined rules, which you can customize to suit your needs.

Here's an example of a Prettier rule that enforces a line length limit of 80 characters:

// .prettierrc.js

module.exports = {
  printWidth: 80
};
How to use ESLint and Prettier in React

To use ESLint and Prettier in your React project, you first need to install them as dev dependencies:

npm install eslint prettier --save-dev

Next, you need to install the ESLint and Prettier plugins for React:

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

You can then configure ESLint and Prettier in your project by creating a .eslintrc.js and .prettierrc.js file respectively. Here's an example configuration:

// .eslintrc.js

module.exports = {
  parser: 'babel-eslint',
  extends: ['plugin:react/recommended'],
  plugins: ['react'],
  rules: {
    semi: ['error', 'always'],
    'react/jsx-uses-react': 'error',
    'react/jsx-uses-vars': 'error'
  }
};
// .prettierrc.js

module.exports = {
  printWidth: 80,
  trailingComma: 'all',
  singleQuote: true,
  jsxSingleQuote: true
};

Finally, you can automate the formatting and linting process by using a pre-commit hook. This ensures that your code is properly formatted and follows best practices before it gets committed to your repository.

npm install husky lint-staged --save-dev
// package.json

{
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
  "lint-staged": {
    "*.js": [
      "prettier-eslint --write",
      "eslint --fix",
      "git add"
    ]
  }
}

Now, whenever you commit changes to your project, Husky will run lint-staged, which will first format your code with Prettier and then run ESLint to enforce best practices. If everything passes, Husky will automatically add the changes to the commit.

Using React, ESLint, and Prettier together can greatly improve your code quality, maintainability, and consistency.