For medium and large front-end projects, project specification and code quality are particularly important. When functional requirements change or you need to refactor, freewheeling (bad) code can be more problematic than new development.
Common problems in front-end project code
1.1 Messy writing style, poor reading experience
This problem is not used to elaborate too much, I think the students who have taken over other people’s code, how many have some experience. To put it simply, code that is too arbitrary is too much for ocD to tolerate, and code that is difficult to read and understand is sometimes as good as tearing it down and starting from scratch.
1.2 Low quality coding and constant bugs
What kind of code is low quality or high quality? Good code can make you feel like you’re reading a novel, bad code can make you look at it and not want to continue, or even look at it for a while.
One might think that this is a problem only for junior programmers, but it is not. Some students with two or three years of experience write code that is still the same. For some students who are not active enough in self-study and have no normative guidance from the team, it is easy to get used to the situation of “studying for half a year and then repeating for three years without any progress”.
It may be hard to believe, but these examples come from real projects. Can you identify as many problems as you can?
Figure 1
Figure 2
Figure 3
Figure 4.
Figure 5
Figure 6.
Figure 7.
These are just a few short examples of what a big piece of complex logic would look like. Use your imagination.
1.3 Functions are not separated, logic is mixed, difficult to read and understand
This kind of problem is actually quite common. Hundreds of lines for a function, thousands of lines for a file, dozens of methods for a class, arbitrary definition of method parameters, no comments, no clear semantics for method and variable names, data modifications and changes interspersed in various methods, and so on. It’s really hard to understand the logic of the code, and you’ll have to read it line by line (and maybe curse at the same time).
The main reason lies in the lack of basic knowledge, coding experience and consciousness of the developer.
In fact, the common open source coding specifications will address this situation. My advice is to brush up on object-oriented programming, functional programming, data structures, common design patterns, take a look at the various open source coding specifications and try to really understand them. When you look back at code from a month ago and see that you can improve or refactor to make the code logic clearer, it shows that you are growing and improving.
It is common to see students in various communities asking questions such as: When a new project is being selected, which of the three frameworks, Vue.js, React and Angular, is suitable? In fact, team development members are experienced with all of these things, and any of them can be; If most of the team members are not experienced in front-end development or the staff is not stable, vue.js is the best choice. Why? Because it’s simpler, simpler, and easier to learn. Vue.js uses hooks such as prop, data, computed, Method and Watch to limit coding methods and styles to a certain extent, so that code written by junior developers is not too ugly, which is one of the reasons why vue. js is gaining popularity in the community.
2. Methods to ensure the quality of front-end project coding
How to ensure the coding quality of front-end projects? In my opinion, there are several ways to think about it: coding specifications, workflow Lint-style mandatory checks, regular Code reviews, unit testing.
2.1 Develop project coding specifications
Coding specifications are especially important on team projects. For junior programmers, due to lack of experience, the requirements of coding specifications can avoid many low-level problems; For multi-person teams, a consistent coding convention can greatly reduce risk and cost during collaborative development, code handover, and so on.
So how should coding specifications be developed?
There is no best style, only a consistent agreement that the team agrees on. Generally speaking, it can be made by the team leader, supplemented by members’ comments, and finally implemented into the team specification and strictly implemented. There are many open source specifications for good front-end teams. Such as:
- Reference presents coding style guide | Chinese
- Reference to an JavaScript Style Guide | Chinese reference
- See Code Guide by @imweb
- Reference fex – team/styleguide
- Reference es6 p-code – style – guide
- See Idiomatic. Js – Principles for writing consistent, easy-to-understand JavaScript
- Refer to the JSDoc Chinese documentation
- Refer to es6 programming style
- Refer to the vue.js style guide
- Refer to the vue.js component coding specification
It’s necessary to learn coding conventions, but can you read them and really understand them?
2.2 Configuring Lint style checking and correction in the development workflow
Introduce tooling assistance into the development workflow to enforce lint validation during code writing and submission. What can be done? All roads lead to Rome. Here is an example of the current popular Git Hook scheme for reference.
2.2.1 Developing editor and Lint tool configurations
We configure the TSLint plugin in our project to validate typeScript; Configure the styleLint plug-in to verify the CSS/LESS.
We agree that the team will adopt vscode editor for development and install at least the following plug-ins to assist development:
- TSLint
- stylelint
- Document This
- EditorConfig for VS Code
- Prettier – Code formatter
- Debugger for Chrome
2.2.2 Adding the.editorConfig file
Because different developers may use different editors, most editors support.editorConfig, so every project should include.editorConfig to uniformly configure the editor’s newline, indent storage format.
Configuration Reference:
# http://editorconfig.org
root = true
[*]
indent_style = space # Use a space instead of a TAB
indent_size = 2 # a TAB is replaced by 2 Spaces
# end_of_line = lf # Newline use the Unix newline \n
charset = utf-8 # character encoding UTF-8
trim_trailing_whitespace = true Remove Spaces at the end of each line
insert_final_newline = true Add a blank line to the end of each file
[*.md]
trim_trailing_whitespace = false The #.md file does not remove Spaces at the end of each line
Copy the code
2.2.3 Configuring Git Hook to enforce coding style detection and correction
With Git Hook, style detection and correction can be performed at the time of code submission. When there is something that cannot be passed, the submission is blocked, thus achieving mandatory implementation of coding specifications.
The following tools can be used to implement this process:
husky
It installs a series of Git hooks into your project.git/hook
Directory, these hooks can be detectedpackage.json
In thescripts
The script commands are configured and executed when the code is submitted (we use it here)pre-commit
Hook)lint-staged
You can retrieve all submitted files and execute the configured task commands in turnstyleLint/TSLint/ESlint
Various Lint verification tools can be configured tolint-staged
The task ofprettier
Configuration tolint-staged
You can implement corrections to auto-formatted coding styles
For configuration information in package.json:
{
"scripts": {
"precommit": "lint-staged",},"lint-staged": {
"*.ts": [
"tslint --fix"."prettier --parser typescript --single-quote --print-width 120 --write"."git add"]."*.less": [
"stylelint --fix"."prettier --parser less --print-width 120 --write"."git add"]},"devDependencies": {
"husky": "^ 0.14.3"."prettier": "^ 1.13.5"."prettier-stylelint": "^ 0.4.2"."stylelint-config-standard": "^ 18.2.0"."stylelint": "^ 9.4.0"."stylelint-config-prettier": "^ 4.0.0"}}Copy the code
. Prettierrc Configuration file Reference:
{
"singleQuote": true."trailingComma": "es5"."printWidth": 120."overrides": [{"files": ".prettierrc"."options": { "parser": "json"}}}]Copy the code
Stylelintrc configuration Configuration reference:
{ "extends": [ "stylelint-config-prettier", "stylelint-config-standard", "./node_modules/prettier-stylelint/config.js" ], "rules": {// Define some rules that fit the team conventions}}Copy the code
With this configuration, when code is committed, the.git/hook/precommit hook is executed in the pre-commit phase. This hook will look for and execute the scrpits precommit command, and lint-staged tasks will be executed one by one. This solution is also a popular one and is used in many open source projects.
Read more:
- Build super-smooth code from Husky and Lint-staged to review the workflow
- How to improve code quality
- Refactoring – Code optimization tips
2.3 Perform Code Review
Coding specifications and Lint checking can only make everyone’s coding style consistent, but they can’t avoid the problem of poor-quality output. This problem is often fatal to the team and the product.
Poor-quality code not only creates low-level bugs that can be detected by testers, but also potentially prolongs the product’s iteration cycle by making a small change in requirements that requires a huge change in code. In addition, when the focus is always on requirements development and bug fixing, the details of product design are not as important (don’t talk to me about refining, but fixing bugs in a rush), which can be disastrous for the product experience.
What code is good and what code is bad? This comes from the accumulation of learning and application of knowledge and development experience. Low – quality coding is all about different levels of experience. For individuals to improve themselves through continuous learning and accumulation, it is necessary for teams to conduct Code Review.
Then how should Code Review be conducted?
Code Review can take many forms. For example, many popular projects on GitHub adopt PR(Pull Request) workflow, and a PR can only be accepted after at least three reviews, which can better guarantee the quality of project code from the process. In some development teams or organizations, a code review platform like Gerrit is introduced, and the process is similar. But for many fast-iterating business product development teams, this multi-person review model is not a good fit: manpower is limited, time is tight, and there is not much to focus on, so even Gerrit becomes a mere formality, and the quality of the code falls on the shoulders of individual developers.
In contrast, regular group discussions, where questions can be quickly answered and summarized, can be more motivating.
Generally speaking, a basic Code Review is necessary when there are new recruits in the team, and the coding specification and style are the focus of the Review. When everyone has a consistent and clear understanding of common basic problems, discussion and learning will gradually become the main content of Code Review.
For teams with a strong internal communication environment, encourage each other to review the submitted code. For most teams, this can be done as follows: The lead person quickly reviews the code submitted by members in the form of spot check, identifies problems and calls back for improvements (students with more problems should focus on their code); In the form of regular (weekly) meetings, the team conducts sampling and summary reviews of the code submitted during the week, learning good coding methods, discussing the reasons for bad coding, and even settling coding conventions suitable for the team.
In addition, the way of operation and expression in the Review process are very important. It should be a way of easy communication and learning, and do not make the Code Review into a criticism meeting.
Read more:
- How does Code Review work? What problems have you encountered?
- How to do Code Review in a human way
2.4 Write unit tests
Writing unit tests for front-end projects is not something many people want to do because the writing process is too complicated. But basic unit tests can be written, changes to common methods and components can create potential bugs for some calling modules, and good unit tests can quickly feed back when something goes wrong.
Our current basic requirements for unit testing projects look like this:
- Public methods, service classes must write unit tests
- Common components should write unit tests that cover as many function points as possible
- Business components can write simple tests
- Pay attention to test code quality, and test code should be repeatedly evaluated and improved through test coverage
Vue. Js /React/Angular frameworks all have perfect unit testing implementation systems. The cost of introducing unit testing into a project is not high, but the process of testing code writing. In some cases I think this “high cost” is worth it. In addition, it should be noted that the execution of unit test must be integrated with CI in order to really play its role of real-time feedback.
2.5 other
2.5.1 Using the static checking language TypeScript/Flow
JavaScript is a weak data type language with simple syntax and flexible usage, and it is this overly flexible nature that allows developers to write arbitrarily, but that arbitrarily comes at a cost and cost.
Sometimes I see some backend students say, well, the front end doesn’t look that hard, I only learned it in a day and I started coding. They may be right, but experienced front-end students who look at the code they’re producing at this point are often horrified. Many front-end development students are not computer-related majors and do not have much basic theoretical knowledge as background. It is more common to “do whatever you want” in code output at the beginning of work.
The fact that TypeScript and Flow have become so popular in the past two years that almost every popular front-end open source product is turning to them is a testament to their importance. Static checking languages can detect and alert potential type reference risks during the coding phase, and can largely avoid many logic bugs caused by careless and misuse. A good type definition makes the logical structure of a project module clearer and more manageable. With the editor’s powerful type hints, code can be written quickly to understand usage without even looking at detailed documentation. Especially in large complex projects, the use of them is definitely more than the disadvantages.
- TypeScript TypeScript Github
- Flow Flow Github
2.5.2 Build a buried page statistics platform
For product quality, monitoring system is a very important part. For the front end, we can collect page information by designing the website buried statistical platform, such as script error, page performance lag and other problems, and analyze the root cause of the problem based on the statistical information, and then fix the problem and improve the code. Of course, statistics do more than that, and I won’t expand too much here.
Read more:
- Teach you how to create a front-end visual monitoring system
- General buried point scheme for front end based on instruction and mixing
- (MZ) Data platform website buried point statistics implementation Principle and Application [PPT]
- Badjs-report – Front-end log reporting and JS exception monitoring
- sentry – cross-platform application monitoring, with a focus on error reporting
3 Related References
What have you learned about front-end coding quality? Welcome to discuss and exchange.
- Angular Coding Style Guide Chinese
- Airbnb JavaScript Style Guide Chinese reference
- Code Guide by @imweb
- fex-team/styleguide
- es6-code-style-guide
- Idiomatic. Js – The principle of writing consistent, easy-to-understand JavaScript
- JSDoc Chinese document
- Es6 programming style
- Vue. Js Style Guide
- Vue.js component coding specification
- Build super-smooth code from Husky and Lint-staged to review the workflow
- How to improve code quality
- Refactoring – Code optimization tips
- How does Code Review work? What problems have you encountered?
- How to do Code Review in a human way
- TypeScript | TypeScript Github
- Flow | Flow Github
- Teach you how to create a front-end visual monitoring system
- General buried point scheme for front end based on instruction and mixing
- (MZ) Data platform website buried point statistics implementation Principle and Application [PPT]
- Badjs-report – Front-end log reporting and JS exception monitoring
- sentry – cross-platform application monitoring, with a focus on error reporting
- LZW. Me/a/the fed – code -…