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
- 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.
- Create react app application
Create React AppIt is a way to create a single page react application officially supported by reactcreate-react-app
Scaffolding command can quickly create a react application, which avoids the trouble of configuring webpack. Our configuration scheme of eslint is based oncreate-react-app
Of the project. - 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。 - 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 toReload
To activate the extension, but to make the extension work, we need to install and configure eslint.
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-app
Execute the CMD command under the projecteslint --init
According to the prompt, we choose to passAnswer questions about your style
The following figure is an example, which can be configured according to the needs of the project
In this way, we have created a custom eslint configuration file, which can be seen in themy-app
A.eslintrc.js
The 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-app
Project, 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.
Ignore specific files and directories
You can create a.eslintignore
Files tell eslint to ignore specific files and directories. Please refer to:Ignoring Files and Directories。
For example: put the bottom.eslintignore
If 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.json
Files, 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.
At this point, we open the error page again, execute the save (Ctrl + s) operation, and you will find thateslint
If 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 Style
Next, we will change the custom eslint configuration to use airbnb coding specification configuration.
First, we need to install two NPM dependency packages:
-
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
-
eslint-config-airbnb, eslint rules that support ECMAScript 6 + and react provided by airbnb, including
eslint
eslint-plugin-import
eslint-plugin-react
as 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.js
File 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.js
In 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.0
The 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.json
The 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"
}
}