Practice front end code specification by using eslint with vscode in react CRA application

Time:2021-1-23

Updated on: January 22, 2019
React.js Create react app project + vscode editor + eslint code checking tool + airbnb coding specification

preface

Why use eslint

In the process of project development, it is particularly important to write code in line with the team coding specification. The program is first for people to see, and then for the machine to execute. In our development work, code maintenance will account for a large proportion, many times we still need to read other people’s code, if there is no unified coding specification, it will bring great trouble to our work.

Therefore, we expect to follow a unified coding specification in the development process, so as to avoid basic syntax errors, code formatting, avoid some usage that is not recommended, and ensure the readability and correctness of the code to the greatest extent. Usually, each team will develop its own coding specification and code style, but it is not enough to only develop the specification. We also need to use code checking tools to enforce the team’s coding specification, such as eslint code checking tool.

This paper will introduce a configuration scheme of eslint, but the configuration of eslint in this paper is based on a certain development environment, focusing on practical application, not the introduction of eslint itself. The configuration of eslint is based on the following environment:

  • React.js Create react app scaffold project
  • Using the vscode editor
  • Coding specification based on airbnb

Related links

  1. Eslint code checking tool
    Eslint (Chinese)Is an open source JavaScript code checking tool, created by Nicholas C. zakas in June 2013.

    JavaScript is a dynamic weakly typed language, which is easy to make mistakes in development. Because there is no compiler, in order to find JavaScript code errors, you usually need to debug constantly during execution. Eslint allows programmers to find problems in the process of coding rather than in the process of execution.

    Eslint is designed to allow programmers to create their own detection rules. All of eslint’s rules are designed to be pluggable. Eslint’s default rules are no different from other plug-ins, and the rules themselves and tests can rely on the same pattern. To make it easy for people to use, eslint has built-in rules. Of course, you can customize the rules during use.

  2. Create react app application
    Create React AppIt is a way to create a single page react application officially supported by reactcreate-react-appScaffolding command can quickly create a react application, which avoids the trouble of configuring webpack. Our configuration scheme of eslint is based oncreate-react-appOf the project.
  3. Vscode editor
    VSCodeMicrosoft’s conscience, is a lightweight and powerful code editor, support windows and Linux. Built in JavaScript, typescript and Node.js Support, and has a rich plug-in ecosystem, you can also install plug-ins to support c + +, C #, python, PHP and other languages, can be called a development tool. Plug in extension:Extensions for the Visual Studio family of products
  4. Airbnb coding specification
    Airbnb JavaScript Style GuideThis project is a popular open source project on GitHub, which is widely used in front-end development. The eslint configuration rule in this paper is based onAirbnb JavaScript coding specification (2.0)andAirbnb react / JSX coding specificationAs a foundation.

Specific configuration method

Installing eslint extension in vscode

Search for eslint in the vscode extension panel and find the installation with the most installation. After the installation, you need toReloadTo activate the extension, but to make the extension work, we need to install and configure eslint.
Practice front end code specification by using eslint with vscode in react CRA application

Create CRA project

Our configuration scheme is tested based on CRA scaffold project, so we need to create a CRA project first. See the official document for detailsCreate React App

The organization structure of CRA project file is as follows:

  my-app
  ├── README.md
  ├── node_modules
  ├── package.json
  ├── .gitignore
  ├── public
  │   ├── favicon.ico
  │   ├── index.html
  │   └── manifest.json
  └── src
      ├── App.css
      ├── App.js
      ├── App.test.js
      ├── index.css
      ├── index.js
      ├── logo.svg
      └── serviceWorker.js

Install eslint

Eslint can choose to install locally:

  npm install eslint --save-dev

You can also install globally:

  npm install -g eslint

It is generally recommended to install globally so that it can work on all our projects. Please refer toEslint NPM document

Creating an eslint configuration file

After the installation of eslint, we need to create a configuration file. In order to demonstrate in detail how eslint works in the actual project, our next operations are carried out in the CRA scaffold project that we have created above, and we do not consider the use of airbnb coding specification first, but first create a more common custom code style.

We’re creatingmy-appExecute the CMD command under the projecteslint --initAccording to the prompt, we choose to passAnswer questions about your styleThe following figure is an example, which can be configured according to the needs of the project
Practice front end code specification by using eslint with vscode in react CRA application

In this way, we have created a custom eslint configuration file, which can be seen in themy-appA.eslintrc.jsThe rules are set according to the selection in the figure above

  /* .eslintrc.js */
  module.exports = {
      "env": {
          "browser": true,
          "commonjs": true,
          "es6": true
      },
      "extends": "eslint:recommended",
      "parserOptions": {
          "ecmaFeatures": {
              "jsx": true
          },
          "ecmaVersion": 2018,
          "sourceType": "module"
      },
      "plugins": [
          "react"
      ],
      "rules": {
          "indent": [
              "error",
              4
          ],
          "linebreak-style": [
              "error",
              "windows"
          ],
          "quotes": [
              "error",
              "single"
          ],
          "semi": [
              "error",
              "always"
          ]
      }
  };

So far, we open it in vscodemy-appProject, you can find that the eslint extension can work normally. Eslint will automatically detect syntax errors and highlight them. At the same time, corresponding error information will be output in the problem window of vscode editor.
Practice front end code specification by using eslint with vscode in react CRA application
Practice front end code specification by using eslint with vscode in react CRA application

Ignore specific files and directories

You can create a.eslintignoreFiles tell eslint to ignore specific files and directories. Please refer to:Ignoring Files and Directories

For example: put the bottom.eslintignoreIf the file is placed in the current working directory, the node in the root directory of the project will be ignored_ modules,bower_ Components and build / directory/ index.js All the files in.

  # /node_modules/* and /bower_components/* in the project root are ignored by default

  # Ignore built files except build/index.js
  build/*
  !build/index.js

Important:Pay attention to the node of the code base_ The modules directory, for example, a packages directory, will not be ignored by default and needs to be added to. Eslinignore manually.

Setting autofixonsave

After the above steps, the eslint extension has worked normally, and the detected errors can be repaired manually according to the error prompts, but this is obviously inefficient and cumbersome. At this time, it is necessary to configure the automatic repair function of the eslint extension.

In vscode, clickFile > Preferences > Settings, opensettings.jsonFiles, searching in settingseslint, you will find that the automatic repair function of the eslint extension is turned off. We modify this item in the user settings on the right to set it to:"eslint.autoFixOnSave": true,In this way, the automatic repair function of the eslint extension is turned on.
Practice front end code specification by using eslint with vscode in react CRA application

At this point, we open the error page again, execute the save (Ctrl + s) operation, and you will find thateslintIf there are many errors in the current page, it may need to be executed many timesCtrl+s

Using airbnb coding specification

We have made eslint work normally in our project, but the code style we use is customized. Sometimes we want to use mature code specifications of some large factories, such asAirbnb JavaScript StyleNext, we will change the custom eslint configuration to use airbnb coding specification configuration.

First, we need to install two NPM dependency packages:

  1. babel-eslintTo enhance the ability of grammar recognition

    babel-eslint allows you to lint ALL valid Babel code with the fantastic ESLint.

    $ npm i babel-eslint
  2. eslint-config-airbnb, eslint rules that support ECMAScript 6 + and react provided by airbnb, includingeslint eslint-plugin-import eslint-plugin-reactas well aseslint-plugin-jsx-a11y

    Our default export contains all of our ESLint rules, including ECMAScript 6+ and React. It requires eslint, eslint-plugin-import, eslint-plugin-react, and eslint-plugin-jsx-a11y. If you don’t need React, see eslint-config-airbnb-base.

    // If using npm 5+, use this shortcut
    $ npx install-peerdeps --dev eslint-config-airbnb

Then we have to modify it.eslintrc.jsFile to use the airbnb coding specification we installed. After modification, the content is as follows:

/* .eslintrc.js */
  module.exports = {
      "env": {
          "browser": true,
          "commonjs": true,
          "es6": true
      },
      "Extensions": "airbnb", // use eslint config airbnb
      "Parser": "Babel eslint" // enhances syntax recognition
      "parserOptions": {
          "ecmaFeatures": {
              "jsx": true
          },
          "ecmaVersion": 2017,
          "sourceType": "module"
      },
      "rules": {
          //Here, you can modify the rules of airbnb as needed. This is just an example
          "linebreak-style": 0,
          "prefer-destructuring": 0,
          "prefer-const": 0,
          "one-var": 0,
          "comma-dangle": ['error', {
              arrays: 'only-multiline',
              objects: 'always-multiline',
              imports: 'only-multiline',
              exports: 'only-multiline',
              functions: 'ignore',
          }],
          "no-console": 1,
          "import/prefer-default-export": 0,
          "import/no-extraneous-dependencies": [2, {'devDependencies': true}],
          "react/prop-types": 1,
          "react/forbid-prop-types": 0,
          "react/jsx-filename-extension": [2, {extensions: ['.js', '.jsx', '.tsx']}],
          "jsx-a11y/anchor-is-valid": 0,

          //The eslint extension of vscode is unable to correct the error caused by this rule
          "react/jsx-one-expression-per-line": 0,
      }
  };

So far, we have completed all the configuration of using eslint with vscode in react CRA application.

error message

In the revision.eslintrc.jsIn the process of using eslint config airbnb, it is found that the eslint extension of vscode can’t automatically repair some of the rules, such as:

  // One JSX Element Per Line
  // https://github.com/yannickcr/eslint-plugin-react/blob/843d71a432baf0f01f598d7cf1eea75ad6896e4b/docs/rules/jsx-one-expression-per-line.md
  'react/jsx-one-expression-per-line': ['error', { allow: 'single-child' }],

Looking up the document of eslint config airbnb, we found that,eslint-config-airbnb v17.1.0The above rule is modified in the version. For details, please refer to:re-enabling jsx-one-expression-per-line allowing single childrenas well asOne JSX Element Per Line (react/jsx-one-expression-per-line)

The eslint extension of the current version of vscode can’t correct the error caused by this rule. Because there is no other solution for the time being, this rule will be closed first.

It can be seen that with the change of vscode or eslint related plug-ins and dependent package versions, some unexpected changes will occur in the configuration. Here is the CRA scaffold project to be testedpackage.jsonThe appendix of the document is as follows;

  /* package.json */
  {
    "name": "my-app",
    "version": "0.1.0",
    "private": true,
    "dependencies": {
      "babel-eslint": "^10.0.1",
      "react": "^16.7.0",
      "react-dom": "^16.7.0",
      "react-scripts": "2.1.3"
    },
    "scripts": {
      "start": "react-scripts start",
      "build": "react-scripts build",
      "test": "react-scripts test",
      "eject": "react-scripts eject"
    },
    "eslintConfig": {
      "extends": "react-app"
    },
    "browserslist": [
      ">0.2%",
      "not dead",
      "not ie <= 11",
      "not op_mini all"
    ],
    "devDependencies": {
      "eslint": "^5.3.0",
      "eslint-config-airbnb": "^17.1.0",
      "eslint-plugin-import": "^2.14.0",
      "eslint-plugin-jsx-a11y": "^6.1.1",
      "eslint-plugin-react": "^7.11.0"
    }
  }