This article introduces some basic concepts of ESLint, and how to configure ESLint in webpack and vscode.
Why do I need ESLint?
JavaScript is different from other languages in that it does not have a pre-compilation checking process. If there is an error in your code, the error will only be exposed after the program is run. This exposure of errors greatly affects the efficiency of development. On the other hand, because JavaScript is a dynamic language, if a team is developing without following a certain specification to write code, everyone adds code according to their own style. As time passes and the amount of code increases, the project becomes more and more difficult to maintain. That’s why front-end developers need Lint tools to constrain and check the code. ESLint is one of the popular Lint tools and the main character of this article.
If you want to learn more about Lint tools, I recommend reading this article: A Comparison of JavaScript Linting Tools
Installation
ESLint supports jsx and ES6 syntax and is highly configurable, which is one of the reasons why it is more popular.
First install eslint
, eslint-webpack-plugin
and @babel/eslint-parser
.
|
|
webpack.config.js
and .eslintrc
Open the webpack.config.js
file and add the following.
Create a new .eslintrc
file in the project root directory, the .eslintrc
file is the configuration file for eslint, add eslint rules to it.
The "parser" "@babel/eslint-parser"
is specified above to make ESLint support the es6 syntax.
ESLint rules
The values of the rules of eslint can be numeric values 0-2
or in array format.
Numeric values 0-2
.
0
: turn off the rule1
: turn on the rule and issue a warning message when the rule is not satisfied2
: turn on the rule and send an error message when the rule is not met
Additional information can also be set using arrays.
extends
If you have multiple projects that need to use the same set of rules, you can publish a package that contains these ESLint rules and simply introduce the package using the extends
field. Many such packages already exist, one of the more popular ones is Airbnb ESLint configuration, which can be found at here for details of the specification it is based on.
Install eslint-config-airbnb
.
|
|
configuration file, add the extends
field.
Configuring ESLint in vscode
You can install the plugin ESLint
in vscdoe and add the following settings to settings.json
.
editor.codeActionsOnSave
means that some lint errors are automatically fixed each time you save, and eslint.validate
means that the supported Languages are validated.