In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the relevant knowledge of "what are the methods of Eslint code inspection". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
One: understand code checking
Code review, as the name implies, is to check the code, which occurs in the development stage, which can effectively help developers reduce JavaScript careless code, such as syntax errors, undefined variables, unused variables, and so on. In addition, code review can also constrain the code style of unified developers, which is conducive to team collaboration.
After the above paragraph, we have reached a conceptual understanding of code review. Next, we will carry out the analysis from three aspects to deepen the practical understanding of code inspection. These three aspects are as follows:
Function of code review
The type of code check
Tools for code review
OK, let's first discuss the function of code review.
1. Function of code review
I think this aspect of code review can probably help us do three things:
Language syntax checking: such as checking string quotation marks or function call parentheses do not match and so on.
Coding error checking: for example, checking that the developer is using a variable that does not exist or that the variable is defined but not used.
Code style checking: for example, checking that developers are not using semicolons (related to the selected style).
Out-of-text summary: the level of the section determines the function of the section.
Now that you understand what this aspect of code checking can do, let's explore the types of code checking.
two。 The way the code is checked
According to the different times and scenarios in which the code review occurs, I classify the code review methods into the following four categories:
Check when coding: check when writing code, usually represented by IDE automatic real-time check and code hints.
Check after coding: check after writing the code, which is usually shown by manually calling the check script / tool to check the code or automatically checking the current file by IDE after the code is saved.
Pre-build check: a pre-build check, usually shown as a pre-aspect of the build task, which automatically triggers the code check at build time.
Pre-commit check: pre-git commit check, which is usually represented by code review as a hooks task of git commit, which automatically triggers code review before code submission.
Doesn't such selfless sharing deserve your likes, attention and encouragement?
It is important to understand the way code review is done, which directly reflects your mastery of the concept of code review itself. Needless to say, let's get into the discussion of code review tools.
3. Code review tool
The implementation of code inspection is usually not just string analysis processing, which involves a lot of parsing. Now that syntax is involved, we need to use different code review tools for different code. Generally speaking, we use the Eslint tool to check the JavaScript and Typescript code, and the stylelint tool to check the style code. This article won't dwell on stylelint, but let's leave the stage to Eslint to explore how to use Eslint to check JavaScript code and typescript code.
OK, before discussing the four code checking methods in order: post-coding check, coding-time check, pre-build check and git pre-submission check, let's connect to Eslint for the project and configure the inspection rules required for various code checking methods.
Second: connect the project to Eslint to check the code.
Many friends may not know Eslint, so let's make a brief introduction to it first.
Eslint is a plug-in (check rules)-based JavaScript code review tool. The concept is concise and concise, it should be noted that the concept says that eslint is an plug-in checking tool, which means that eslint is designed to decouple the checking tool from the checking rules. That is, after installing eslint's development dependencies, we can and need to choose to install a check rule that we like.
Okay, that's all for the theory, and then we'll get the real knowledge from practice, and the practical steps are as follows:
Step1: installation check tool eslintyarn add eslint-- devstep2: install and configure check rules
Before we explore the configuration of installation inspection rules, it is necessary to make clear what our inspection objectives are. In my opinion, the check target is naturally the pre-build code, and it is the code written by your own / your own team (not a third-party module). After all, the ultimate goal of the check is to fix the service, we are only responsible for repairing the code written by our own / our team, the built code and third-party code will not and should not be fixed by us even if the check does not pass us.
Inspection rules usually take two forms in a project, namely:
Rules configured in the configuration file: the main form, which declares a large number of rules by inheritance and extension
Magic comments in project code: a secondary form, usually used as a special case of rules in a configuration file
Generate the eslint configuration file:
For configuration files, we usually use the eslint-- init command to generate this configuration file. The following table lists some configuration problems that often occur after invoking this command (not necessarily the following).
Note: I think we should be more careful in answering these questions, because the answer to the question will affect the configuration, the configuration will affect the inspection rules, and the inspection rules will affect the check results. Of course, the purpose of answering these questions is to generate the desired configuration file, and you can modify the eslint configuration file directly if the question is answered incorrectly or if there are subsequent changes to the rules.
Serial number function question 1 choose the use of eslint, often choose 3How would you like to use ESLint? (Use arrow keys)
To check syntax only
To check syntax and find problems
To check syntax, find problems, and enforce code style2 choose the modularization specification What type of modules does your project use? (Use arrow keys)
JavaScript modules (import/export) only
CommonJS (require/exports)
None of these3 selects the framework used by the project, Which framework does your project use? (Use arrow keys)
React
Vue.js
Does None of these4 use TypescriptDoes your project use TypeScript? Choose the environment in which the code will run (multiple selections) Where does your code run? (Press to select, to toggle all, to invert selection)
() Browser
() Node6 chooses how to define the style for your project, often 1How would you like to define a style for your project? (Use arrow keys)
Use a popular style guide
Answer questions about your style
Inspect your JavaScript file (s) 7 chooses to use the specific popular code style Which style guide do you want to follow? (Use arrow keys)
Airbnb
(https://github.com/airbnb/javascript)
Standard
(https://github.com/standard/standard)
(https://github.com/google/eslint-config-google)8 chooses the configuration file format, usually 1 (more flexible) What format do you want your config file to be in? (Use arrow keys)
JavaScript
YAML
Magic comments in JSON code:
In addition to configuring rules in the configuration file, eslint also has a way to patch rules through magic comments in the code, as shown in the following example:
/ / shielding the entire line of code to check const str1 = "${name} isa coder" / / eslint-disable-line / / to block a rule: no-template-curly-in-string rule for this line const str1 = "${name} isa coder" / / eslint-disable-line no-template-curly-in-string
Warm reminder: the name of the rule can be obtained from the check result prompt or output information.
Third, based on Eslint and its rule implementation
As for the explanation of a workflow, I prefer to demonstrate a simple demo directly. With this line in mind, let's demonstrate an example of Eslint checking JS code and an example of Eslint checking TS code, respectively. According to the logic of code review, I will follow the following ideas when I demonstrate and explain demo, namely:
Target problem code
Code review rule configuration
Code review actions and results
Fix code operation
OK, let's move on to Eslint's discussion of checking examples after coding JS code.
Check the JS code example after 1.Eslint coding
1): target problem code
Const noUsedVar = 1; function fn () {console.log ('hello') cnsole.log (' eslint');} fn (fn2 ()
The above few lines of code can represent the three parts of the eslit code review, which are:
Grammatical error
Coding error: undefined, not used
Coding style: no semicolon
2): code review rule configuration
Through eslint-- init, the eslint configuration file is obtained after answering questions according to the project characteristics:
Module.exports = {env: {browser: true, es6: true,}, extends: ['airbnb-base',], globals: {Atomics:' readonly', SharedArrayBuffer: 'readonly',}, parserOptions: {ecmaVersion: 2018,}, rules: {},}
3): code review operations and results
The first round of check results first reported syntax errors, after fixing the syntax errors, the second round of checks reported a lot of coding and style errors. Correlating the results of the two checks to the problem code gives the following analysis:
Const noUsedVar = 1; / / find program:'noUsedVar' is assigned a value but never used function fn () {console.log ('hello') / / enforce code style:Missing semicolon (semicolon) cnsole.log (' eslint'); / / find program:'cnsole' is not defined} fn (/ / syntax error fn2 (); / / find program:'fn2' is not defined
4): fix the code
Repair is carried out according to the above inspection results. For errors caused by inconsistencies in the style of the code, most of the problems can be automatically fixed through the parameter fix. On the other hand, most of the syntax and coding errors can only be fixed manually by the developers themselves. After manual and automatic fixes, the problem code may look like this:
Import {fn2} from'. / test2'; function fn () {console.log ('hello'); console.log (' eslint');} fn (); fn2 (); check the TS code example after 2.Eslint encoding
1): target problem code
Function foo (ms: string): void {console.log (msg);} foo ("hello typescript~")
2): code review rule configuration
After the project installs the typescript dependency (executing eslint without first installing the typescript dependency-- init will report an error), the eslint configuration file is obtained after answering questions (typesrcipt yes) according to the project characteristics through the eslint-- init command:
Module.exports = {"env": {"browser": true, "es6": true}, "extends": ["airbnb-base"], "globals": {"Atomics": "readonly", "SharedArrayBuffer": "readonly"}, "parser": "@ typescript-eslint/parser" "parserOptions": {"ecmaVersion": 2018}, "plugins": ["@ typescript-eslint"], "rules": {}}
As opposed to JavaScript's code review, checking for typescript requires an additional syntax parser (that is, the parser configuration item content in the above configuration).
3): code review operations and results
After checking with the-- fix parameter, eslint mainly reported two coding errors, which are mapped to the file and analyzed as follows:
Function foo (ms: string): void {/ / 'ms' is defined but never used console.log (msg); / /' msg' is not defined} foo ('hello typescript~')
4): fix the code
In this example, after fix automatically fixes the code style, manually change the parameter of the foo function to msg.
Function foo (msg: string): void {console.log (msg);} foo ('hello typescript~'); IV: implementation based on Eslint and its rules
When it comes to coding, checking has to mention code hints, and we have to contact the IDE we specifically choose to use. In addition, in order to ensure the unified configuration of code inspection rules in various ways, the key thing we need to do is that IDE can read the eslint rule file we configured in the project to check the code in real time.
Since individuals mainly use VScode for development, the demo and discussion below are defaulted to the vscode environment. Official related information: Eslint's official list of integration tools [1. Install eslint, configure eslint rules] (https://marketplace.visualstudio.com/items?item>Visual Studio Code: ESLint Extension documentation.
To tell you the truth, I also learn and sell this thing now. After all, there are too many things to learn at the front end, and the original intention of this article is not to cover all aspects of a certain technical point, but to help you build a systematic understanding and guidance.
Because we need to be able to read the eslint rules under the read project when IDE real-time code is checked. So the following two steps are essential:
Install eslint, configure eslint rules
Installation configuration related to IDE Real-time Code Review function
According to the idea of the above implementation steps, let's do a demo to check when coding based on Eslint and its rules in vscode environment.
1. Install eslint, configure eslint rule yarn add eslint-- dev # install eslint-- init # initialize configuration
The rule configuration of eslint has been discussed above, so I won't repeat it here.
Installation configuration related to 2.IDE Real-time Code Review function
After the eslint tool and the inspection rules are ready (that is, the rules for IDE code review), the rest of the specific check behavior triggers and code hints will be left to IDE to implement. For vscode, our implementation idea is to install the extension eslint (personal use of the version 2.1.14, the following configuration 1.x is probably not applicable), and then pay attention to turn on vscode's eslint code check function (the eslint switch under vscode is the lower right corner of the eslint text logo) to achieve real-time eslint code check in the vscode environment.
Configure the real-time inspection function of IDE
If you need to configure the real-time inspection feature of IDE, you can find the relevant configuration file by opening setting-> find eslint-> opening setting.json of vscode. The following is an example of configuring vscode code inspection feature:
/ / configure eslint "editor.codeActionsOnSave": {/ / automatically fix "source.fixAll.eslint": true} when saving, "eslint.quiet": true, / / warning does not report a red underscore, and can be used to deal with the real-time code of warning burst by no-console rules to check and repair the error.
During the automatic check of IDE, you can modify the check rule file under the project (.eslintrc.js) if you report a code violation. For example, an individual encounters a rule error of ESLintExpected linebreaks to be 'LF' but found' CRLF' in demo practice, and its situation is somewhat special. It will report real-time inspection in IDE, but it will not report when manually calling the eslint command. The specific reasons are not analyzed here. Individuals can directly add the following rules to the rules file (.eslintrc.js):
Rules: {'linebreak-style': [0,' error', 'windows'],}, V: implementation based on Eslint and its rules
Let's go directly to today's more commonly used gulp and how webpack build tools implement pre-build checks.
1.gulp pre-build check
The idea to check the aspect of this code through gulp is as follows:
Install eslint and initialize the eslint configuration file
Download and install the gulp-eslint plug-in
Write code for js file processing to check the section
1): initialize the eslint configuration file
Yarn add eslint-dev eslint-init
2): download and install the gulp-eslint plug-in
Yarn add gulp-eslint-dev
3): write code for js file processing to check the aspect
Examples are as follows:
/ /... The other code const eslint = require ('gulp-eslint'); const script = (0 = > {return src ([' scripts/*.js']). Pipe (eslint ()) / code check. Pipe (eslint.format ()) / / outputs the lint results to the console. Pipe (eslint.failAfterError ()) / / lint error, the process exits, and the build ends. Pipe (babel ({presets: ['@ babel/preset-env']})) .pipe (dest ('temp')) .pipe (bs.reload ({stream: true}))} / /. Other code 2.webpack pre-build check
The idea of checking the aspect of this code through webpack is as follows:
Install eslint and initialize the eslint configuration file
Install eslint-loader
Write a webpack configuration file and add this eslint-loader to the js file
(1): install eslint and initialize the eslint configuration file
Yarn add eslint-dev eslint-init
(2): install eslint-loader
Yarn add eslint-loader-dev
(3): write a webpack configuration file and add this eslint-loader to the js file
Rules: [{test: / .js$/, exclude: / node_modules/, use: ['babel-loader',' eslint-loader' / / later]}] VI: implementation based on Eslint and its rules
In this part of the explanation, I will discuss how Eslint implements git pre-submission checking step by step from the following four aspects:
1.git pre-submission check principle: Git Hooks
Using husky implementation: write node code instead of shell code
Implementing hook task flow: using lint-staged to cooperate with husky to achieve
Implement git pre-submission check: execute eslint task first and then git add task
Let's move on to the first point, the principle of git pre-submission inspection: the discussion of Git Hooks.
1.git pre-submission check principle: Git Hooks
Eslint implements the pre-submission check of git through Git Hooks. Git Hook is also known as git hook. Each hook corresponds to a task. Through shell script, you can write the specific actions to be performed when the hook task is triggered.
This article focuses on implementing code checking before git submission, so we focus on git commit as a hook, using the following steps:
Write hook tasks: for the project. Create a new pre-commit file under the git/hooks folder
#! / bin/sh echo "before commit"
Trigger hook: execute the git commit command under the project
After the git commit command is executed, you can see the output before commit information regardless of whether the commit operation is successful or not.
The above method is available, but it is not suitable to be used in actual production. After all, it is difficult for front-end developers to use shell to write git hook. Let's introduce the use of husky as a library to help us achieve the goal of writing hook tasks in js code.
two。 Using husky implementation: write node code instead of shell code
The implementation steps are as follows:
(1): install husky
(2): configure the hook task of husky: the following package.json task
(3): trigger hook: git add-> git commit
1): install husky
Yarn add husky-dev
After installing this module, it can be installed in. You can see the following newly added files under the git/hooks folder.
2): configure the hook task of husky: the following package.json task
"scripts": {"test1": "echo before commit", "test2": "node test2.js"}, "husky": {"hooks": {"pre-commit": "yarn test2"}}
3): trigger hook: git add-> git commit
After the git commit command is executed, we can trigger the hook task written by js code that we implemented through husky.
Let's enhance that through the library lint-staged, so that hook supports not only single tasks but also task flow triggers.
3. Implementing hook task flow: using lint-staged to cooperate with husky to achieve
The implementation steps are as follows:
(1): install husky and lint-staged modules
(2): configure the hook task flow of husky: the following package.json tasks
(3): trigger task flow: git add-> git commit
1): install husky and lint-staged modules
Yarn add husky-dev yarn add lint-staged-dev
2): configure the hook task flow of husky: the following package.json tasks
"scripts": {"precommit": "lint-staged"}, "husky": {"hooks": {"pre-commit": "yarn precommit"}, "lint-staged": {"* .js": ["echo task1", "echo task2", "echo task3"]}
3): trigger task flow: git add-> git commit
Practice has found that, compared with a single husky module to implement a single task, only the successful execution of git commit commands (with add resources and submission information) will trigger operations in lint stage, and these operations will only be valid for js files.
Well, after laying the groundwork above, we can move on to the final requirement we want to implement, that is, the implementation of git pre-submission checks.
4. Implement git pre-submission check: execute eslint task first and then git add task
The implementation steps are as follows:
(1): install husky and lint-staged modules
(2): configure the hook task flow of husky: the following package.json tasks
(3): trigger task flow: git add-> git commit
1): install husky and lint-staged modules
Yarn add husky-dev yarn add lint-staged-dev
2): configure the hook task flow of husky: the following package.json tasks
"scripts": {"precommit": "lint-staged"}, "husky": {"hooks": {"pre-commit": "yarn precommit"}, "lint-staged": {"* .js": ["eslint-- fix", "git add"]}}
3): trigger task flow: git add-> git commit
After downloading and configuring these development packages, after we perform git commit, we will trigger the pre-commit hook task of husky configuration, and this hook task will hand over the task to lint-staged to deal with, and then through lint-staged to achieve code inspection of js files and automatic style repair (or errors will be interrupted after submission) re-add, and then execute the commit task to ensure that the code must be checked before submission.
This is the end of the content of "what are the methods of Eslint code checking". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.