What is Eslint
Coding standards
Every programmer has his or her own coding habits, the most common being:
- Some people write code that has to end with a semicolon
;
Some people don’t want a semicolon;
Look better; - Some people don’t write more than 80 characters in one line of code, and they think it looks neat. Some people like to write all their logic in one line of code, and they think it’s cool to write code that no one else can understand.
- Some people use variables without having to define them first
var a = 10;
, while careless people may write variables without defining them and use them directlyb = 10;
;
The meaning of Lint
It doesn’t matter if you’re writing your own project, but in the company the boss wants everyone to write code that is consistent with the rules, so that other people can read the source code, because the source code is consistent with the code specification.
So the problem is, the boss can’t check every line of code everyone writes, it’s a stupid thing. All repetitive tasks should be made into tools to save money. This tool should do two things:
- Provide coding specifications;
- Provide automatic code inspection procedures, and print inspection results: tell you which file which line of code does not conform to which code specification, so that you can modify the code.
Lint was born from this.
The meaning of Eslint
Lint is a generic name for tools that validate code formatting, such as Jslint, Eslint, and so on………..
2. Use Eslint
Make sure you have Node and NPM installed on your computer
Create a project
The NPM init directive generates a package.json file in the project root directory.
支那
$ d:
$ cd d:
$ mkdir test-eslint
$ cd test-eslint
$ npm init
Copy the code
Installing dependency packages
–save-dev installs esLint into the devDependencies property of the package.json file, which means that the package is only used during development and is no longer needed at launch.
支那
$ npm install eslint --save-dev
Copy the code
Set up the package.json file
Open package.json and modify the script properties as follows:
支那
"scripts": {
"test": "react-scripts test --env=jsdom",
"lint": "eslint src",
"lint:create": "eslint --init"
}
Copy the code
- The script property means script and is used by typing in a CMD window
NPM run command
In the form of:npm run lint:create
; "lint:create": "eslint --init"
This script is used to generate.eslintrc.js files. In the introduction to Lint it was stated that Lint should provide the coding specification. The specification is written in this file wherever it is written, so we need to create it;"lint": "eslint src"
Lint should provide a program that automatically validates code. This script allows Lint to automatically validate all.js files in the SRC directory.
Create the.eslint.js file
$ npm run lint:create
> 20170811@0.1. 0 lint:create D:\code\test\20170811
> eslint --init
? How would you like to configure ESLint? Answer questions about your style // Create a configuration file in the form of a question and answer
? Are you using ECMAScript 6 features? Yes // Whether to verify Es6 syntax
? Are you using ES6 modules? Yes // Whether to verify Es6 module syntax
? Where will your code run? Browser // Code running environment, Browser refers to the Browser
? Do you use CommonJS? Yes // Whether to check CommonJs syntax
? Do you use JSX? Yes // Whether to verify JSX syntax
? Do you use React? Yes // Check React syntax
? What style of indentation do you use? Tabs // Select Tab or Space for the first line
? What quotes do you use for strings? Double // Use single quotation marks 'string' or double quotation marks 'string'
? What line endings do you use? Windows // Operating system
? Do you require semicolons? Yes // Whether to add a semicolon to the end of each line of code;
? What format do you want your config file to be in? JavaScript // Generate the configuration file in.js format
Installing eslint-plugin-react@latest // We need to download the React syntax package to verify the Reac syntax
Copy the code
Create the index.js file
Create a SRC /index.js file in the root directory with the following content, and then use Eslint to verify that the.js file conforms to the encoding specification.
const lint = 'eslint'
Copy the code
The directory structure should be:
- test-eslint
+ .eslintrc.js
+ package.json
- src
+ index.js
Copy the code
Check the code
$ npm run lint
1:7 error 'lint' is assigned a value but never used no-unused-vars
1:14 error Strings must use doublequote quotes
1:22 error Missing semicolon semi
3 problems (3 errors, 0 warnings)
2 errors, 0 warnings potentially fixable with the `--fix` option.
Copy the code
Here are three errors reported:
- Index. js line 1, character 7, error encoding rule is
no-unused-vars
The: variable lint is only defined, but not used; - Index. Js line 1, character 14, error encoding rule is
quotes
: encoding specification Strings can only use double quotes, but single quotes are used here; - Index. js line 1, character 22, error encoding rule is
semi
Each line of code must end with a semicolon.
Once we are familiar with the coding specification, we can make a uniform code style by making only responsive changes. If you are initially unfamiliar with a specific rule in the coding specification, you can check its usage in the ESLint rule table. (It is not recommended to memorize the rule table, but to use what to look up, it as a dictionary to use, not so tired)
Set the –fix parameter
Open package.json and modify the script properties as follows:
支那
"scripts": {
"test": "react-scripts test --env=jsdom",
"lint": "eslint src --fix",
"lint:create": "eslint --init"
}
Copy the code
Note: “lint”: “eslint SRC –fix”, plus –fix, is a function provided by ESLint to automatically fix basic errors.
If you run NPM run Lint, you will see two missing error messages, not that the coding specification has changed, but that Eslint automatically fixes the underlying error, opens the index.js file, and you will see the string automatically changed to double quotes and a semicolon at the end of the code. Unfortunately, the fix only fixes basic errors that do not affect the code logic, such as no-unused-vars, which can only be modified manually.
Configuration File Description
The default.eslintrc.js configuration file is generated as follows:
// .eslintrc.js
module.exports = {
"env": {
"browser": true,
"commonjs": true,
"es6": true
},
"extends": "eslint:recommended",
"parserOptions": {
"ecmaFeatures": {
"experimentalObjectRestSpread": true,
"jsx": true
},
"sourceType": "module"
},
"plugins": [
"react"
],
"rules": {
"indent": [
"error",
"tab"
],
"linebreak-style": [
"error",
"windows"
],
"quotes": [
"error",
"double"
],
"semi": [
"error",
"always"
]
}
}
Copy the code
This file exports an object containing the env, extends, parserOptions, plugins, and Rules attributes. As beginners to Eslint, we want to learn as much as we can about what each attribute is and what it does, just to get a little bit of security.
Env, parserOptions, plugins
These three will be put together because you only need to know what they are: I use ES6, React, and JSX syntaxes in my program, and these properties allow Eslint to check these syntaxes. You don’t need to know any more than that.
The author wasted a lot of time in this section at the beginning of learning. After reading the official document for many times, most of them could not understand its meaning. Later, I thought that since it provides such a tool to automatically generate configuration files and the way of command line interaction, I only need to tell it that I need to use ES6, React and JSX syntax. It will automatically configure it to meet my requirements.
extends
I’ve been saying that checking your code follows a coding specification, but what exactly is that?
An extends property with a value of “ESLint :recommended” enables a set of core rules that have been proven as best practices (that is, coding specifications that most people think they should follow). If you want to know what the best practices are, Rule items marked √ can be viewed in the ESLint rule table.
Eslint-config-airbnb is someone else’s custom code specification if you don’t like the default rules provided by Npm. Configure “extends” in our own.eslintrc.js: The prefix “airbnb”, eslint-config can be omitted so that we use the rule in eslint-config-Airbnb instead of the official rule “extends”:”eslint:recommended”. For details about how to create and share custom rule configurations, see: How do I Customize Rule Configurations
A few words about the “Airbnb” coding specification, most authors working with most open source projects use the “Airbnb” coding specification rather than the official “extends”: “ESLint :recommended” coding specification.
If we feel that certain rules in the eslint-config-Airbnb rule configuration do not meet the requirements of the current project, we can directly configure the rules property in.eslintrc.js to take precedence over the shared rule airbnb.
rules
Configuration files are also generated, so how do we know what rules our system will follow?
In the previous example, the use of NPM run lint check out the three mistakes, if string of our project is to use single quotes, not double quotes, end code is either a semicolon is good-looking, variable is defined may not use, we can set up rules to define our own code conventions, the rules.
ESLint comes with a large number of rules, which should be modified according to the following requirements:
- “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 with error level: error (when triggered, the program will exit)
Some rules have no attributes and only need to be turned on or off, like this: “eqeqeq”: “off”, while others have their own attributes, which can be used like this: “quotes”: [“error”, “double”]. See the ESLint rule table for built-in attributes.
Modify the rules property in.eslintrc.js:
"rules": { "indent": [ "error", "tab" ], "linebreak-style": [ "error", "windows" ], "quotes": ["error", "single" // "string" must be enclosed in single quotes instead of double quotes, 'string' does not return an error, "string" returns an error], "semi": ["error", "never" // change the end of the code without a semicolon], "no-unused-vars": 0 // 0 is equivalent to off, indicating that the rule is disabled.Copy the code
NPM Run Lint is used to verify the code. If no error is reported, the verification passes and the code conforms to the unified coding specification.
D:\code\test\20170811>npm run lint
> [email protected] lint D:\code\test\20170811
> eslint src
D:\code\test\20170811>
Copy the code
Possible doubt
I’m new to ESlint and don’t know what rules to do. Would you like to go to the ESlint rule table and memorize them? The answer is no.
Personally, I don’t think ESlint’s configuration files are created in one go, but are refined over the course of a project. You can rest assured bold encoded first, and then use the NPM run lint check code coding standards, if by this time error, can know which is in the error message coding standard error, you may not know them, now go to eslint rule table query the use of the corresponding rules, such as: No-unused-vars, so as to further determine whether this coding specification is needed in the project. If necessary, local adjustment can be made.
$ npm run lint
1:7 error 'lint' is assigned a value but never used no-unused-vars
1:14 error Strings must use doublequote quotes
1:22 error Missing semicolon semi
3 problems (3 errors, 0 warnings)
2 errors, 0 warnings potentially fixable with the `--fix` option.
Copy the code
A few common rules
"Quotes" : [1, "single"], # single quotes "quote - props" : [2, "the as - men"], # double quotes automatically change single quotes "semi" : [2, "never"], # Do not end a line with a semicolon "comma-dangle": [1,"always-multiline"] # Add a comma to the last value of an object or arrayCopy the code
Three, use scenarios
1. Vscode’s ESLint plugin helps you format your code automatically
Use ESlint for code checking when saving in VScode
1.1 enable ESLint
Install the ESLint plugin and extension Settings for the plugin. Select “Settings” in the lower left corner of VSCode to open the VSCode configuration file and add the following configuration
Add the following configuration to settings.json
Eslint. AutoFixOnSave is used for automatic formatting when saving, but only JS files are supported by default.
This way you can check and do some simple fixes every time you save based on the ESLint rule you configured in the.eslintrc.js root directory
2. Install the esLint package in the React/Vue project and configure.exlintrc.js to override the rules introduced in Node-modules by importing the company-specified ESLint rules in the.exlintrc.js package or directly specifying your own rules.
Four, reference
- Github.com/standard/st…
- eslint.org/
Five, summary 1
1. [Grammar rules] Generally include:
- Two characters indent
- Use single quotes
- Statements cannot be followed by semicolons
- , etc.
2. Lint is a generic name for a tool that validates code formatting
- The specific tools are
Jslint
、Eslint
等
3. The ESLint plugin for VSCode helps you format your code automatically
- Install the eslint plugin directly, and every time you save it, vscode will be able to red flag any deviations from eslint rules, as well as make some simple self-corrections.
4. ESLint is an open source JavaScript validation tool that compares toJSLintESLint is configurable
Other differences from JSLint:
- ESLint uses Esprima for javascript parsing
- ESLint uses the AST to modify code schemas
- ESLint is fully plug-in, each rule is a plug-in, and users can add more plug-ins at run time
5. JavaScript verification comparison
JavaScript validation: JSLint, JSHint, JSCS, ESLint
-
JSLint, ancient, non-configurable, non-extensible, and cannot disable validation for many features
-
JSHint, the configurable version of JSLint
-
JSCS, code style checking, only catches problems related to code formatting, not potential bugs or errors. Already merged with ESLint.
-
ESLint, easy to extend, allows you to customize rules and install more rules as plug-ins.
A linting tool is a good step towards problem solving, but it finds errors based on rules and has limitations.
For more secure automated bug collection, unit tests, code reviews are recommended.
Vi. [Best Configuration] Recommended coding specifications for JavaScript
There are a number of recommended coding specifications for JavaScript, of which the following two are well known:
- airbnb style
- javascript standard
AlloyTeam’s eslint-config-alloy is also recommended here.
But the code specification is something that is best worked out between team members to make sure that everyone can accept it, and if there is a disagreement, the majority rule. Although the title of this section is Optimal configuration, there is no optimal solution in the software industry, and even javascript Standard is not a javascript standard coding specification. It is simply called what is best.
Amway: ESLint and Prettier used together to unify not only coding conventions but also code styles.
Why do I use JavaScript Standard Style?
Please refer to the blog.csdn.net/u012207345/…
Amway a good program hierarchy
Programmers should pay attention to:
- correctness
- readability
- happiness
- High efficiency
As it turns out, using JavaScript Standard Style is good for each of these.
8, 【ESlint principle 】
Ast Abstract syntax tree
JSLint and JSHint parsed code in a top-down manner, and the early JavaScript syntax didn’t change for thousands of years. In this way, the code can be quickly parsed to find possible syntax errors and irregularities. However, since the release of ES6, JavaScript syntax has changed a lot, such as arrow functions, template strings, extension operators… JSLint and JSHint cannot detect ES6 code without updating the parser. ESLint, on the other hand, takes the AST approach to statically analyzing code, while retaining great extensibility and flexible configuration capabilities. This also tells us that in the daily coding process, it is important to consider the subsequent scalability.
Because of this powerful extension capability, many of the industry’s JavaScript coding specifications can be quickly implemented across teams, and the team’s own custom code specifications can also be shared.
Finally, hopefully you’ve understood the benefits of ESLint, learned how to use ESLint, and been able to introduce ESLint to existing projects to improve the quality of your code.
Use/write the ESLint plugin
There are hundreds of rules to choose from, but that’s not enough, because the official rules only check standard JavaScript syntax, and if you’re writing JSX or Vue single-file components, ESLint’s rules start to fall into place.
In this case, you need to install an ESLint plug-in to customize certain rules for checking. Plugins for ESLint have the same naming format as extensions, starting with eslint-plugin-, which can also be omitted when used.
npm install --save-dev eslint-plugin-vue eslint-plugin-react
Copy the code
{
"plugins": [
"react", // eslint-plugin-react
"vue", // eslint-plugin-vue ]
}
Copy the code
An extension is a plugin that loads the plugin.
{
"extends": [
"plugin:react/recommended", ]
}
Copy the code
10. Conclusion two
Vue/ React project: vscode install esLint plugin
2. Add the auto-fix -fix parameter to the NPM run script object when the NPM lint command is executed
3. What is the difference between installing ESLint and react? Vue/ React projects install ESLint, vscode install esLint.
Webpack is a compilation error that will stop compilation until you fix it. Vscode is a reminder for you to see the error directly. Will help you fix simple errors by the way.
Eslint is the loader in webpack. The full name is ESlint-loader. Loader is a loader that processes certain files, so it is essentially a loader. Vscode is an editor, and eslint in vscode is essentially a vscode plug-in that calls eslint and reports eslint errors back to vscode, and that’s it. What’s the difference between Webpack and Webpack-CLI? You can see the contrast