Introduction: With the growth of the business and the rapid increase in the number of members of the development team, many of the new people come from all over the world, with different coding styles and habits. Usually in the mutual Codereview found a lot of code problems, over time the code appeared code is difficult to maintain the problem, even will appear low-level errors. Therefore, I tried to do some exploration in the front-end code quality control, but also summed up some experience to share with you. Author: Zheng Zhenbo

Overview of this paper

  • Coding standards
  • Redundant files and code

1. Coding specification

In some old projects we often encountered the following problems:

1.1 Formulation of coding specifications

How to develop coding specifications? This is a constant topic, and there have even been instances of developers constantly changing esLint rules according to their own habits and desires. Yes, very subjective developers do this, and they end up with a bunch of esLint rules.

If you are objective, you might think in these three ways:

  • Take care of the habits: Try to take care of the habits of the members of the team. People are individual and it seems impossible to take care of them.
  • Strict rules: the more strict the rules, the better, and never let him loose.
  • Cast a vote: Voting seems to be the most democratic decision, but often the most controversial rules show little difference in votes.

If you can get results from these three methods, you’re the boss, and it’s all too easy. In any case, each extended rule can be found to have support and refutation points. Students usually express their opinions on several points when making specifications:

  • Habits: “I do it all the time, no problem”
  • Industry standard: “Look at the open source code of a big company.”
  • Necessity: “I’ve never seen a JS that can’t run without a semicolon at the end of a line.”
  • Time: “Pressing TAB once saves more time and effort than pressing TAB twice; A semicolon at the end of a line is a waste of life.”

1.2 Balance between coding quality and coding efficiency

Is there a way to settle these arguments? How to strike a balance? “Eslint rules”, “prettier”, “eslint-config-standard”, “Airbnb”, etc., should be considered in the selection of code specifications:

  • Technology selection suitable for the project: for example, our team technology stack uses React, Node.js, ES6, so it is clear how to choose the direction.
  • High community recognition: Believe that the community is as contentious as the team members, if a specification gets more than 1W stars, it is already a big deal.
  • Plugin support: Supports ESLint, JSCS, etc.

Based on the above criteria, we chose over 8W + esLint rules maintained by the Airbnb front end team. How to get team members to adapt quickly after standards are set?

  • Configuration editor: if VSCode is used, you can configure “esLint. autoFixOnSave”: true. In this way, when saving the code, it will automatically fix the code according to ESLint rules.
  • Editor plugin: If you use VSCode, you can install the Eslint plugin, which will prompt for non-standard code in real time.

  • If you are using WebPack, you can use eslint-Loader, which in conjunction with eslint-friendly-formatter can give developers a good hint. See this article webPack introduction to ESLint for details

This is where the ESLint specification first hits the ground.

1.3 Rectify the ancestral code

Once the specification is customized and in place, what about the heirlooms? So we come across a different voice:

  • I didn’t write this code: “Whoever writes it fixes it.”
  • I dare not change: “change the problem to take the blame for how to say”
  • Change it next time: “In a hurry to release it, or change it next time.”
  • Eslint-disable: “disable great method, nothing can stop me”

Here’s how we can fix the heirlooms: First, see how bad the problem is:

npx eslint src
Copy the code

1.3.1 Add.eslintignore to exclude third-party JS files

However, it is found that most of these errors are from third-party libraries that are not NPM packages. These files often do not meet current coding standards, and some of them are compressed, and should not be checked by ESLint. To block the third party documents after testing, the remaining eslint errors and 2 w +, error classification:

1.3.2 about CRLF

In text processing, each operating system has its own set of standards:

Dos and Windows use “Carriage return + line feed, CR/LF” to indicate the next line; In UNIX/Linux, LF is used to indicate the next line. Macs (MAC OS) use “CR” to indicate the next line.

So, if you have a Windows player on your team, the new line for creating a file is CRLF, which is not a big drawback, but if you have a Vim or Emacs player opening a file, you’ll see something like this:

  • Set IDE newlines such as VSCode:

  • VSCode default configuration: file – preferences – Settings – search: default end-of-line character. Modified to\n
  • EditorConfig: Even better if you have an EditorConfig in your project:

#Unix-style newlines with a newline ending every file [*] end_of_line = lf insert_final_newline = true

  • Git config: You can convert your code to LF when you commit gitgit config core.autocrlfYou may have seen this configuration before, but it may not be used correctly. In fact, it has 3 values to configure:

False: No conversion is required when git pull. Input: Convert LF to LF when git pull

The thing you should be using here is the Git conifg core. The messenger LF input (for example, initiating a change) and then interacts with a messenger. Either of those should solve your line feed problem.

1.3.3 Automatic Repair

With all that out of the way, it’s time to try and get ESLint to auto-fix: NPX ESLint SRC –fix

1.3.4 Regular rectification

800+ errors are distributed on each page, so each team member can be assigned several pages to fix and go online in batches. The most important thing for such a large-scale fix is post-release monitoring:

1.4 Once thought ESLint was everything

While you might think that because ESLint did not report an error, O**K is often not easy to spot, as in this example:

The introduction of absolute paths
Relative path introduction

1.5 Follow the rules

We set the rules, the code changes, and then we need to stick to the rules, or it’s all for nothing

  • Git hook: Git hooks can be configured using tools such as pre-commit, Husky, and so on. With NPM script, esLint can be executed to check if the changed files conform to the specification before committing the code, otherwise exit has a non-zero value to terminate the Git commit. However, there are drawbacks to using Git hooks on the front end. For example, you have to wait for ESLint every time you commit your code, resulting in a greatly reduced development experience. Some students will delete the pre-commit hook file to bypass the detection. You can also add--no-verifyTo turn off detection.
  • Web hook: The advantage is that the server is used for verification, which cannot be bypassed in the front end. The disadvantage is that the server resources are needed. For more information on how to build web hooks, please refer to this article

1.6 Other considerations about the front-end code specification

You can also use stylelint to check the stylelint format for CSS, but these are more about formatting code. If you want to write good code, ESLint and the like are not all that useful. For example, if you want to write clean code, here are a number of patterns you can use. This is where ESLint can’t help you, so ESLint isn’t everything.

2. Redundant files and codes

2.1 About Redundant Files

You might think of redundant files as a problem, but it’s not a critical pain point. If your team is a sticky-ass, clean-code freak, then redundant files should be a big concern. Even if you’re an old timer, it’s possible to generate redundant files.

2.2 Why Are Redundant Files Generated

In the process of code iteration, it is often easy to ignore to delete the corresponding file. There are about two scenarios: 1. Delete the require in JS code, but forget to delete the corresponding file (img/ CSS/JS /etc.). Delete background from CSS, forget to delete the corresponding image file. Deleting code is fun, as long as the page refresh a wave without error feel o**k, the accumulation of redundant files slowly make the whole warehouse bigger and bigger.

2.3 Clearing Redundant Files

If you build with WebPack, you can easily analyze the dependencies of the entire project. Step 1: Run the command from the root directory to import the file dependencies to stats.json. This step took a little longer, I ran it once in the project and it took 35s for 1420 files.

webpack --json > ./stats.json
Copy the code

Step 2: Use glob to obtain all file paths in the directory:

glob('! (node_modules)/**/*.*')
Copy the code

Combined with the stats.json generated in the first step, you can filter out files that are not referenced.

2.4 Redundant code

2.4.1 About redundant CSS

In fact, it is difficult to analyze redundant CSS in a project. There are three main reasons: 1. Nesting of elements or components of the page: it makes it impossible to judge whether the style has been applied to the corresponding elements only from the level of static analysis. 2, style global domain: a style declaration in a. SS, it can be applied to any DOM on the page, so the analysis must traverse all the DOM and CSS in the project, a style declaration needs to check all dom, if there are N style declarations, it will have a very large amount of calculation. 3. CSS has no constraints: The styles of multiple CSS files can also be applied to a DOM element. Because open source UI libraries are often used, the styles of corresponding DOM elements will be overwritten according to the design requirements, so this too flexible feature brings uncontrollable and difficult to manage.

2.4.2 Solving the Redundant CSS

You can explicitly declare which class styles apply to the DOM. This ensures that the styles of one component do not affect other components:

eslint-plugin-css-modules

2.5.1 Redundant JS

During code iterations, it’s possible to remove the use of methods, leaving a Class with redundant methods that are hard to detect by ESLint because there’s no way to tell if they’ll be used at any point after they’re instantiated. If you want to find these redundant methods, you also need to analyze all JS dependencies from the whole project, which can be very computative and time-consuming.

2.5.2 Try to solve redundant JS

There is no good way to solve this problem, but it can be analyzed in two ways: 1. Naming convention: for example, if the methods beginning with an underline are private methods, then we can only analyze whether all private methods in this file are used. 2. Comment tags: If you don’t like underlining, consider adding comments.

2.6 Redundant files/Code summary

1) Delete code carefully 2) analyze redundancy 3) use tools properly 4) monitor after release