1. The original intention of introducing scanning tools
1.1 For pain points
Now find a lot of code when it is applied in combing the front-end non-standard parts, including simple js and code formatting problems, cause the loss of the code readability, the other a variety of historical code is “different”, an application is from “all” person safeguard, difficult to suffer “cantonese mee tianjin goubuli” all kinds of taste, More unavoidably, there are “smelly congenial”, these situations seriously affect the quality of application. Application development members mostly due to before is to develop the back-end, inexperienced front-end development as well as many front knowledge system are now learning slowly accumulated in the process of development, in addition, still, always want to for the front-end application code quality whether there are such as Java development code scanning plug-in, similar to the front end of the code quality scan plugin to handle. After referring to the materials, ESLint + Husky + Prettier + Lint-staged method was used to improve the front-end quality to a certain extent. The pain points are as follows:
- Code specification landing difficult: Code code is equal to the team and the company of the whole technical team collaboration contract, at the same time, these specifications are through many senior master through the baptism of the project are precious legacy in developing less go a lot of detours, but, in the face of the present situation of the development specifications often face is difficult to be born, is always “robbing Peter to pay Paul”, The bottom line is that you need tools to enforce that code must be scanned by code development specifications;
- Low quality code for online applications: In the actual development situation, developers can simply execute git push operation to bring local code to remote branch. If the code quality is low, it is easy to have hidden trouble for online application quality. As for CR during merge, the feedback link is too long, and the best way is to commit locally. At the very least, ensure that the current code meets the development specifications set by the team. If not, the commit will not succeed, so that the code quality problems can be guaranteed from the source.
- The code format is difficult to unify: According to the status quo of the development team members to the code format is very different, even like some strings in double quotes, some people like to use single quotation marks, and so on, if do not have a unified code formatting issues, always feel each other always feel funny to see other people’s code, code format confusion, even seriously affected the code readability, Undoubtedly, it also increases the cost of communication within the team. In this case, a tool is needed to ensure that the format of the code within the team is consistent.
- Code quality culture is difficult to be implemented: through the introduction of code quality tools, code quality can be constantly restricted to their own code quality in the development process, and gradually cultivate their own “cleanliness” development concept of code quality, but also become a starting point for the team and their own quality culture implementation.
For the above pain points, tools such as ESLint + Husky + Prettier + Lint-staged can be used to solve the above problems effectively. The execution process and principles are given below (CR, another starting point for code quality culture, can also be seen in “Entering Ali for a Year”). Thoughts on code-review).
1.2 Effect Achieved
To nip in the bud, to prevent potential problems of code to the online environment, is the best way to submit your code in the local can scan out the potential errors, and forced to be modified to submit, so as not to carry the problem code to online, you can make online code at least not the existence of low-level programming errors. Husky, Lint-staged, ESLint, and Prettier plug-ins can be used to achieve this desired effect:
As shown in the figure above, when attempting to commit code, it cannot commit because it is scanned for errors and must be modified successfully before committing.
1.3 Configuration File
Add the following files to package.json in the front-end application:
{
"scripts": {
"precommit": "lint-staged"
},
"lint-staged": {
"src/**/*.js": [
"eslint --fix --ext .js"."prettier --write"."git add"]},"devDependencies": {
"eslint": "^ 5.0.0"."eslint-config-ali": "^ 2.0.1." "."eslint-plugin-import": ^ "server"."eslint-plugin-react": "^ 7.1.0"."husky": "^ 0.14.2"."babel-eslint": "^ 8.1.1"."lint-staged": "^ 4.0.0"."prettier":"^ 1.16.4"."eslint-plugin-prettier":"^ 3.0.1." "."eslint-config-prettier":"^ 4.0.0"}},Copy the code
Add.eslintrc.js scan rule:
module.exports = {
"extends": ["eslint-config-ali"."prettier"."plugin:prettier/recommended"]."parser": "babel-eslint"."rules": {
"prettier/prettier": "error"."strict": "off"."no-console": "off"."import/no-dynamic-require": "off"."global-require": "off"."require-yield": "off",},"plugins": ["prettier"]."globals": {
"React": "readable"}};Copy the code
Add.prettierrc.js file to format code after a scan (optional, if prettier is not included, remove configuration from package and eslintrc)
module.exports = {
printWidth: 80,
semi: true,
singleQuote: true,
trailingComma: 'none',
bracketSpacing: true,
jsxBracketSameLine: false,
arrowParens: 'avoid',
requirePragma: false,
proseWrap: 'preserve'
};
Copy the code
Just introduce the above configuration files into the front-end project, so that the effect of 1.3 can be achieved. The implementation principles are analyzed below, if you are interested, you can continue to read
2. Implementation principle
2.1 Execution Process
To achieve the above effect, the process is as follows:
- Git add adds the code to the staging area.
- Git commit;
- Husky registered hook functions are called before Git pre-commit, performing Lint-staged;
- Lint-passage Takes all submitted files and executes written tasks (ESLint and Prettier);
- If there is an error (that doesn’t pass ESlint), stop the task, print an error message, and wait for the fix before executing commit;
- Commit successfully, which can be pushed to remote
In the above process, there are several core points:
- Husky registers git hook functions to ensure that code scans are called when git commits.
- Eslint completes scanning according to configured rules;
- Lint-staged projects guarantee that only files currently added to git stage will be scanned. The reason for this is that if entire project files are scanned and code rules have not been detected prior to the project, hundreds or thousands of errors will occur, which will lead to crashes. Therefore, only the current ADD files are detected to achieve timely loss, and the historical code can be cut to the new branch for repair before merging.
2.2 Plug-in Description
In the execution process of 2.1, PLUG-INS such as ESLint and Lint-staged are mainly used. These plug-ins are described below.
2.2.1 eslint
What is Lint?
Lint is a tool for statically scanning front end code according to code rules. It is mainly used to inspect current local code for its specifications. If it does not conform to the currently formulated specifications, Lint will report an error. This ensures the quality of the online code.
Why was ESLint introduced?
Introducing ESLint in my thinking has the following advantages:
- Since it is a code scanning tool, it can naturally ensure the landing of the development protocol, such as the Java development protocol scanning plug-in. For the front end, ESLint is a tool that configures the code specification to ensure that the specified code specification is landing. Common code specifications of some large factories have Ali front-end specifications, Airbnb, Goose factory AlloyTeam team, etc.;
- Ensure the online quality of the application, which goes without saying. With the use of other tools, code that does not meet the code specification cannot be pushed to a remote branch.
- For higher readability, ESLint scans code quality and, commonly used in conjunction with Prettier, formats code after passing the code specification to ensure readability.
- Avoid low-level errors through
eslint --fix
Some low-level problems in the code can be corrected according to the specification.
How to use ESLint?
The code specification for esLint configuration is also provided in eslintrc.js. The code specification is naturally specified according to the status of the team. We currently use the Ali front-end specification ESlint-config-Ali, but of course it could be “tailored” to the current situation. It should also be noted that the globals variable is configured in the eslintrc.js configuration file:
"globals": {
"React": "readable"
}
Copy the code
This is because the React framework used on the front end, ESLint will scan variables such as React and report a no-undefined error. You need to set it as a global variable to avoid scanning. Rules are configurable in esLint’s design and can be set in the rules property. Rules for specific ESLint can be seen in the official documentation, where the check box is esLint :recommended rules.
2.2.2 husky
The best way to do this is to make sure that the local code has passed the check before pushing it to the remote, so as to ensure the online quality of the application to a certain extent. It also avoids the problem of having too long a feedback process for Lint.
So when do you start a scan? This is the natural time to do a local Git commit. It would be best if you could trigger a code check during a local Git commit. This is the Git hook you need to use.
What are Git hooks
Git hooks are used in the hooks directory of the.git file, which contains some examples of hooks used in git operations. Git hooks can be used to trigger a code scan during a local commit to ensure the quality of local code. Read this article about Git Hook.
2.2.3 lint – staged
Using ESLint and Husky can guarantee code quality issues, but in real engineering you have to face a problem. In reality, an application is generally involved in multiple development, and personnel changes are also involved in the application life cycle, which means that an application is jointly maintained by people from all over the world. It is difficult to avoid “Cantonese burning wax, Tianjin goubuli” various tastes, and more unavoidably “smell of the same”.
If you were to submit code against this history and check every other unmodified file for hundreds or thousands of errors, you’d probably delete the configuration to manage ESLint and break out in a cold sweat. As shown below (from the network)
Modify A file, B, C, D and other files all the errors appear. To solve this problem, only scan the files after the current modification each time, that is, scan the files that git add adds to the stage area to complete the check of the incremental code. How do you do that? This is where you need to use lint-staged tools to identify files that have been added to the stage section. Lint-stage you can look at the official documentation for lint-stage, and now you can go back and look at the package.json file to see what it means:
"scripts": {
"precommit": "lint-staged"
},
"lint-staged": {
"src/**/*.js": [
"eslint --fix --ext .js",
"prettier --write",
"git add"
]
},
Copy the code
A Git hook will be triggered and precommit will be executed when git commit is performed. The precommit script references lint-staged configuration to only scan files that Git has added to stages. Lint-staged configuration does three things: 1. Run the ESLint –fix operation to scan and fix any problems that the tool can fix; 2. Execute the prettier script, which formats code, specifically below; 3. 3. Add the code again after the above two tasks are completed.
2.2.4 prettier
Prettier is used to format code. Eslint also does some formatting but mostly scans code for specifications while Prettier formats code. Prettier is used to format code. Prettier compares the code before formatting with the code after formatting, and if it finds a difference, Prettier marks it and fixes it according to a formatting convention. The diagram below shows Prettier’s ability
As you can see, Prettier formats code so it’s readable. Perttier can support a variety of formats such as JSX, HTML, etc. See official documents for details, and the code formatting standards can be determined according to the status of the team.
Plugins that work with ESLint
Eslint-plugin-prettier: eslint-config-prettier: Eslint-config-prettier: ESlint-plugin-prettier: eslint-config-prettier: ESlint-config-prettier: ESlint-config-prettier: eslint-config-prettier: eslint-config-prettier Prettier – This plugin is used when esLint’s rule conflicts with Prettier’s (mostly unnecessary) rule, such as when ESLint limits single quotes while Prettier does, so if ESLint drives Prettier to check code, Both types of errors will be prompted, although they both point to the same code error, at which point the plug-in will turn off additional errors. Eslint-config-prettier can be found in its documentation.
3. IDE plug-in supporting use
In the actual development, suitable plug-ins can be installed in IDE to improve the development efficiency. After installation, there will be red wavy line prompt if there is any non-conforming place in the code, and there will be a one-button fix function, which can improve the efficiency. Take WebStorm as an example
How to install plug-ins for ESLint
As shown, in WebStorm you only need to specify the esLint configuration file.
The method of installing the Prettier plug-in
As shown in the figure, Webstorm already has prettier built-in, just make sure the package prettier has been installed in the current project.
4. Write at the end
Through the introduction of these tools to a certain extent to ensure the quality of the application, and can achieve twice the result with half the effort. But at the end of the day, improving code quality requires an internal contract and a team of like-minded people. The quality of the code can ensure the minimum “cleanliness”, if and coder this cause, confirmed that he is the right person, then please live with him for the rest of his life, heart, all is you.
5. References
Check husky and pre-commit before git commit
Semi-automatically improve project code quality using ESlint and Lint-Staged projects
Build super-smooth code from Husky and Lint-staged to review the workflow
Front-end grooming uses ESLint and Prettier to check and format code problems
AlloyTeam ESLint Configuration guide
Use ESLint+Prettier to unify front-end code styles
Manage projects with esLint + prettier + pre-commit
React-native ESLint & Prettier & pre-commit Hook configuration
Manage projects with esLint + prettier + pre-commit
Prettier introduction and basic usage of Prettier