Official website of esLint: eslint.org/
If you’ve ever studied javascript, you know that javascript is a very informal language. You can use either single or double quotes on strings. A line of code can end with or without a semicolon. These features of the JavaScript language result in different styles of JavaScript code written by different people. If the project is jointly developed by many people, the code style in the whole project will be disunified and chaotic, although it does not affect the execution of the code.
In order to keep the js code style consistent across projects without changing the way programmers write code, ESLint was created to make rules for JavaScript code and format it for us automatically. With ESLint, programmers don’t have to change the style of their code. When code is saved or git is committed, esLint automatically formats the code and makes the code look uniform throughout the project.
If ESLint could only rule js and format JS code, that would be too low. Eslint can also manage vue, Angualr and other mainstream front-end framework code, so learning to use ESLint is essential.
Next, let me take you step by step into ESLint
Environment to prepare
Initialize the NPM project
Go to the new directory and execute the following command to initialize an NPM project
npm init
Copy the code
This step creates a new package.json file in the directory
2. Install the ESLint NPM package
npm instll eslint --save-dev
Copy the code
The –save-dev here means that esLint is a package that will be used during development and will not be needed after release, when the dependency will not be packaged
Eslint configuration
Generate configuration file command
To use ESLint, you need to have an ESLint configuration file and configure your own code style. You can quickly generate the corresponding configuration file using commands
npx eslint --init
Copy the code
Detailed configuration process
Generated configuration file
The esLint configuration file.eslintrc.json is now automatically generated with the rules we configured above, as follows
{
"env": {
"browser": true.// Allow to run in a browser
"es2021": true.// New ES2021 features are allowed
"node": true // Allow allow on node
},
"extends": "eslint:recommended".// The recommended code style
"parserOptions": { // esLint parser
"ecmaVersion": 12."sourceType": "module"
},
"rules": { // Code custom style
"indent": ["error".4]."linebreak-style": ["error"."windows"]."quotes": ["error"."single"]."semi": ["error"."never] } }Copy the code
“Extends “: “eslint:recommended” means that configuration of ✓ in rules Page will be enabled using the recommended code style
Rules is our own code style, where “quotes” and “semi” are the names of esLint rules. The first value of this rule is the error level of the rule, which can be the following values
"off"
或0
– Do not use this rule"warn"
or1
– Warning, does not affect the code operation"error"
or2
– Error preventing code from running
These three error levels allow you to fine-grained control of esLint’s application rules
Disable unnecessary configurations
In the configuration file generation process, one step is for you to choose what type of newline you use. In a multi-person project, it’s not appropriate to choose anything because someone might be using Windows and someone might be using MAC, and the two types of operating systems use different newlines. Windows uses CRLF and MAC uses LF, so you need to turn this check off, otherwise a certain type of person is bound to report a line break error
As described in the previous section, simply change the first parameter of the corresponding rule to “off” or “0”. The configuration is as follows
"rules": { // Code custom style
// ...
"linebreak-style": ["off"."windows"].// ...
}
Copy the code
Eslint code checks and fixes
1. First, create a new index.js file in the project root directory and write the following code
let aaa = "hello eslint";
function sayHello(){
console.log("hello eslint");
}
Copy the code
Remember to save after writing or modifying, otherwise ESLint will check for unsaved code
2. Run esLint to check the code in index.js
npx eslint .\index.js
Copy the code
In addition to the quotes and semi errors we configured ourselves, there are also no-unused-vars and no-mixed-spaces-and-tabs errors due to the use of the recommended code style, which is the “extends” in the configuration file: “Eslint :recommended” code
3. Use ESLint to fix code
npx eslint .\index --fix
Copy the code
Note here that the configuration file has four Spaces for indentation, so if the indentation is not four Spaces, it can be fixed by using –fix
In this case, it’s a bit special because the indent uses both a space and a TAB, so –fix can’t fix it
5. Manual repair
Run the ESLint code fix command again
npx eslint ./index.js --fix
Copy the code
The code was successfully repaired without any errors reported
Vscode uses the eslint plugin
Eslint now has a general idea of how to use commands to check for code that doesn’t fit our style and fix it. Now, I’m going to introduce a simpler and more user-friendly way to check and fix code than using the command line, which is the eslint plugin for vscode.
Using the ESLint plugin, you can alert us to non-standard code during development and use the plugin’s quick fixes, which is very convenient
Prettier is often used as the prettier plug-in for formatting code, so I recommend turning it off or uninstalling it because formatting code using ESLint does not require other plugins
Installing the Configuration Plug-in
1. Install the ESLint plugin
2. Configure VScode to automatically repair code when saving
Open vscode Settings, select the workspace, and then open the configuration file
Enter the following configuration in the configuration file
{
"editor.codeActionsOnSave": { // Do something while saving the file
"source.fixAll.eslint": true // Use esLint to fix code}}Copy the code
This configuration code can also be found in the introduction of the ESLint plugin
instructions
It is recommended to use workspace to configure VScode, so that each project will automatically generate a.vscode directory, which contains a setting.json file, which stores the relevant configuration of vscode of the current project. This method has two advantages:
- Realize configuration isolation, different project configuration is not the same, do not conflict
- This configuration can be uploaded to Git when multiple people collaborate, making it easier for everyone to use the same configuration
test
We’ll use the code in index.js that we used earlier
You can see that the code in question is drawn directly with a red wavy line. If you place the mouse over the wavy line, you can directly see the reason for the error
The esLint plugin automatically fixes the code for us, since the save time fix was previously configured, so the shortcut CTRL + S saves the code directly
But as with command line fixes, some problems are unfixable
Because there are both Spaces and tabs in the indent, the indentation problem needs to be fixed manually, and if there are only tabs or Spaces, the ESLint plugin will fix it for you
No-unused-vars indicates an error
Method one:
The aaa variable and the sayHello function are defined but not used, so they are redundant
We can comment out the extra code, or use it where we need it, and the problem goes away
Method 2:
If you know anything about promises, you know that promises take two arguments, resolve and Reject, but sometimes you don’t use the reject parameter, as shown in the figure below
The reject parameter is not used, but if the reject parameter is removed, the promise feels missing, so you can remove this code check
As you can see from ESLint, the name of this rule is no-unused-vars and the “extends” in the configuration file: The “eslint:recommended” property enables the no-unused-vars rule, so it can be turned off in a configuration file
"rules": {
/ /...
"no-unused-vars": ["error", {"vars": "all"."args": "none"} // Check variables, not parameters]}Copy the code
The second parameter to “no-unused-vars” can be either a string or an object.
The default value for “vars” is “all” and the default value for “args” is “after-used”
Vars (variables)
The Vars option has two Settings
- “All” : checks all variables, including local variables, global variables, and functions
- “Local” : checks only local variables
Args (parameters)
The args option has three Settings
- “After-used” : only the parameters after the last used parameter are checked
- “All” : checks all parameters
- “None” : parameters are not checked
Eslint checks vUE code
Eslint can check not only formatted JS code, but also VUE code, which requires minimal configuration to use
You’ll need to use vscode’s eslint plug-in, which was introduced in the previous section, to make code checking easier
Environment set up
Create a VUE project
vue create vue-eslint-example
Copy the code
Just choose the first one, vUE will automatically install ESLint for us
Check the package. The json
Vue automatically installs esLint-related dependencies for us, so read on
And esLint can be configured in package.json
Of course we can configure the style we need in this, but I prefer to configure ESLint in a separate configuration file for clearer structure of the project
Generating a Configuration File
When creating a vue project, if you choose to install ESLint, VUE-CLI will automatically install ESLint-related dependencies for you, and you can configure ESLint directly in package.json, but to make the project clearer, I prefer to use the eslint command to generate a separate configuration file in which to configure ESLint. Of course, we can also configure directly in package.json, depending on personal preference
Of course, we don’t have to worry about these two configurations colliding because ESLint reads configuration files with precedence:
.eslintrc.js > .eslintrc.yaml > .eslintrc.yml > .eslintrc.json > .eslintrc > package.json
Package. json has the lowest priority, feel free to create other types of configuration files, but it is best to remove the configuration from package.json as it is redundant, although it does not affect us
Then use the command to generate the ESLint configuration file
npx eslint --init
Copy the code
The options for the command are the same as in the previous [ESLint configuration](## ESLint configuration) section, with the exception of a few modifications as follows:
Here, since we use vue framework, we choose vue. Js
Here we choose a more popular style, the first is just a novice demo, development will generally choose this
There are three popular styles here, we can click on the corresponding links to see their styles
According to the official documentation, here is a brief list of the differences between the three styles
- Airbnb: By default, the string uses single quotation marks and ends with a semicolon
- Standard: By default, single quotation marks are used for strings without semicolons at the end
- Google: String uses single quotation marks and ends with a semicolon
Because OF my habit of not ending with a semicolon and using single quotes on strings, I prefer the Standard style
Finally, we generate the configuration file eslintrc.json that we need
Modifying a Configuration File
In the generated configuration file, the configuration is as follows
"extends": [
// add more generic rulesets here, such as:
// 'eslint:recommended',
"plugin:vue/essential"."standard"
// 'plugin:vue/recommended' // Use this if you are using Vue.js 2.x.
]
Copy the code
First, this “extends” configures a set of common rules
"plugin:vue/essential"
: VUE official rules, similar"plugin:vue/recommended"
Each configuration has different code requirements. More vue plugins can be found in the official documentationeslint-plugin-vue"standard"
: popular JS code specification, which we selected manually earlier
This plugin recommends using recommended, which requires vue code to be more demanding, such as v-if in HTML tags before other attributes, a single line for each attribute, the position of methods and data in
, etc. So it would be better to say “essential” instead of “recommended”.
"extends": [
"plugin:vue/recommended"."standard"
]
Copy the code
Vscode configuration
In vscode, if we want to use the eslint plugin, we also need to configure vscode, and it is recommended to use workspace configuration mode, so that eslint will fix the code for us automatically when saving the file
What does the official eslint-plugin-vue documentation say
Visual Studio Code
Use the dbaeumer.vscode-eslint (opens new window)extension that Microsoft provides officially.
You have to configure the
eslint.validate
option of the extension to check.vue
files, because the extension targets only*.js
or*.jsx
files by default.Example .vscode/settings.json:
{ "eslint.validate": [ "javascript"."javascriptreact"."vue"]}Copy the code
If you use the
Vetur
plugin, set"vetur.validation.template": false
to avoid default Vetur template validation. Check out vetur documentation (opens new window)for more info.
This means that esLint only works with *.js or *.jsx files by default. If you want to format vue, you need to configure eslint.validate
And, if you have any loading vscode Vetur plug-in, you should also configure “Vetur. Validation. The template” : False to avoid conflicts between the two. Vetur is a necessary plug-in for vue development in vscode, so this configuration must be written
Therefore, the final configuration is as follows
{
// Save using esLint fix code
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
// Let ESLint check formatted Vue code, only JS code by default
"eslint.validate": [
"javascript"."vue"].// Disable the Vetur plugin for lint and use eslint to avoid conflicts
"vetur.validation.template": false
}
Copy the code
This is all configured, open the.vue file, write non-standard code and ESLint will recognize it directly
We save the file and ESLint automatically formats the code
summary
That’s all there is to say about how esLint can be used, and there are many more uses that aren’t covered here, so it’s up to you to figure them out. I think the best way to learn is to read official documents, cultivate the ability of reading and understanding, combined with their own hands-on ability, then the learning efficiency will be very high