preface

When you come to a new team or take on a new project, there are bound to be code specification issues. As the front-end application becomes more and more complex, the problem of code specification is getting more and more attention. This article takes you through the configuration of a React front-end application from scratch.

For example, eslint-prettier-react-demo

Create a project

First, we use the official scaffolding create-react-app to create a project:

npx create-react-app eslint-prettier-react-demo/
cd eslint-prettier-react-demo/Copy the code

Eslint

Install dependencies

Eslint is a tool that can examine code and report on it. Its goal is to ensure code consistency and avoid errors. Eslint provides code validation for the ECMAScript/JavaScript specification. You can configure it according to your individual/team code style, or you can use an open source configuration scheme. This article uses ESLint-config-Airbnb.

Eslint is powerful because of its active open source community and flexible plugin mechanisms. In this article, we need to configure a React project, so we can choose some plugins suitable for the open source community to help us achieve our goals.

  • Eslint-plugin-import: This plug-in is mainly used for validationimport/exportSyntax to prevent misspellings of file paths and export names
  • Eslint – plugin – JSX – a11y: providejsxElement accessibility verification
  • Eslint-plugin-react: verifies react
  • Eslint-plugin-react-hooks: verifies the use of hooks against the hooks API

Next, we install these dependencies:

npm i -D eslint eslint-config-airbnb eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-react eslint-plugin-react-hooksCopy the code

Modifying a Configuration File

Next, let’s configure these plugins according to the Eslint documentation. Run the following command on the console:

./node_modules/.bin/eslint --initCopy the code

We can choose the corresponding configuration according to the requirements of the project. After execution, you can see an.eslintrc.js file in the root directory of the project.

Eslint supports configuration files in a variety of formats, with the following priorities:

  • 1、 .eslintrc.js
  • 2、 .eslintrc.yaml
  • 3,. Eslintrc. Yml
  • 4,. Eslintrc. Json
  • 5. Eslintrc
  • 6, package. Json

We’ll just use the official recommended.eslintrc.js format.

Next, let’s open the file with our favorite editor, and I’ve added some comments to make it easier to understand:

module.exports = {
    An environment defines a set of predefined global variables
    "env": {
        "browser": true."es6": true
    },
    // A configuration file can be inherited by enabled rules in the underlying configuration.
    "extends": [
        "airbnb"].// Customize global variables
    "globals": {
        "Atomics": "readonly"."SharedArrayBuffer": "readonly"."_": true."$": true,},// ESLint uses Espree as its parser by default. You can specify a different parser in the configuration file
    // "parser": "@typescript-eslint/parser",
    // Configure the syntax supported by the parser
    "parserOptions": {
        "ecmaFeatures": {
            "jsx": true
        },
        "ecmaVersion": 2018."sourceType": "module"
    },
    // ESLint supports the use of third-party plugins. Before using the plug-in, you must install it using NPM.
    // When configuring plug-ins in a configuration file, you can use the plugins keyword to store a list of plug-in names. The eslint-plugin- prefix can be omitted from the plugin name.
    "plugins": [
        "react".// "@typescript-eslint"].// ESLint comes with a lot of rules. You can use comments or configuration files to modify the rules to be used in your project. To change a rule setting, you must set the rule ID to one of the following values:
    // "off" or 0 - turns off the rule
    // "WARN" or 1 - Turn on the rule and use a warning level error: WARN (will not cause the program to exit)
    // "error" or 2 - enable the rule, using error level error: error (when triggered, the program will exit)
    "rules": {
        semi: 0.'no-unused-vars': [
            1,
            {
                vars: 'all',
                args: 'after-used',
                ignoreRestSiblings: true,
                varsIgnorePattern: '^ _',
                argsIgnorePattern: '^_|^err|^ev' // _xxx, err, error, ev, event}].'no-useless-escape': 2,}};Copy the code

Prettier

We can use Eslint to improve the quality of our code, but there is no guarantee of a uniform code style. Prettier a common code style is valuable to a team, so Prettier can be used when saving and submitting code. This also reduces the cost of Code Review. It will not replace Eslint, so it will need to be used with Eslint.

Configure the application

1. Install dependencies

npm i -D prettier eslint-config-prettier eslint-plugin-prettierCopy the code

2, modified Exlint configuration, open. Eslintrc. Js file, increase in the extension “plugin: prettier/it” :

    "extends": [
        "airbnb"."plugin:prettier/recommended"
    ]Copy the code

3, Add the prettier configuration file and create.prettierrc.js in the root directory of the prettier file:

module.exports = {
  "printWidth": 120.// The number of characters in a line. If more than 80 characters are added to the line, the default value is 80
  "tabWidth": 2.// A TAB represents several Spaces. The default is 2
}Copy the code

Check on submission

If prettier is used to optimize code submitted with Git, there are tools available to do so.

  • Husky: A handy one to handlepre-commitpre-push 等 githooksThe tools
  • Lint-staged: Run linters’ tools for code in Git staging

1. Install dependencies

npm i lint-staged husky -DCopy the code

2. Add configurations

// package.json
{
  .
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged"}},"lint-staged": {
    "src/*.{js,jsx,mjs,ts,tsx}": [
      "node_modules/.bin/prettier --write"."node_modules/.bin/eslint --fix"."git add"]."src/*.{css,scss,less,json,html,md,markdown}": [
      "node_modules/.bin/prettier --write"."git add"]}.
}Copy the code

3. Test the commit command

This is where we try to add a component and commit the code. It was found that the submission could not be made, and an error was reported:



That’s because prettier’s default rule, andairbnbInconsistent rules.

Here you can refer toConfiguration in the Git example, adjust it.eslintrc.jsFile.

If you submit the code, you will see:

Configure the VS Code editor

1, Find and install the plugin ESlint, Prettier in the VS Code store

2. Edit settings.json to find the corresponding configuration file:

  • Windows %APPDATA%\Code\User\settings.json
  • macOS $HOME/Library/Application Support/Code/User/settings.json
  • Linux $HOME/.config/Code/User/settings.json

Then add the following parameters:

  "files.autoSave": "onFocusChange"."editor.formatOnSave": true."editor.formatOnType": true."eslint.autoFixOnSave": true."eslint.enable": true.Copy the code

This will automatically optimize the file format when we save the file.

Here, the construction of the whole project, as well as the editor Settings are completed! 🎉 🎉 🎉

reference

  • How to integrate Eslint & Prettier in React
  • Use the ESLint && Prettier specification code format
  • Use ESLint+Prettier to unify front-end code styles
  • Use ESLint+Prettier specifications for React+Typescript projects
  • ESLint application practices in medium and large teams
  • prettier
  • eslint