当前位置:   article > 正文

前端代码审查工具_前端代码审查中应检查的内容

pascalcase本地检测

前端代码审查工具

If you are part of a front-end team with several talents (including you), hundreds of commit might be pushed every day. Indeed, no matter the team methodology you use to deliver new features, each developer is working on a specific functionality.

如果您是拥有多个才华(包括您)的前端团队的一员,那么每天可能会推动数百次提交。 的确,无论您使用什么团队方法来交付新功能,每个开发人员都在致力于特定的功能。

In order to validate their changes, a developer should ask for a Merge Request (or Pull Request) to merge these changes into the common branch (the one used for reference). Other front-end developers will make a code review.

为了验证其更改,开发人员应请求合并请求(或请求请求)以将这些更改合并到公共分支(用于参考的分支)中。 其他前端开发人员将进行代码审查。

A code review is important for four reasons:

代码审查很重要,原因有四个:

  • You can check if the code fulfills the specifications.

    您可以检查代码是否符合规范。
  • You are informed about the code modifications, which will potentially lead you to change your modifications on your active branch or suggest some enhancements.

    您将获得有关代码修改的信息,这可能会导致您在活动分支上更改您的修改或提出一些增强建议。
  • It’s a good practice to guarantee a quality code.

    保证质量代码是一个好习惯。
  • It’s a way to share experiences, tips, and coding skills.

    这是一种分享经验,技巧和编码技能的方法。

Let’s see together what you should inspect in your next front-end code review.

让我们一起看看在下一个前端代码审查中应检查的内容。

An image representing a code review colors for changes
Image source: Author
图片来源:作者

To review code changes, we will focus on five main topics:

为了查看代码更改,我们将重点关注五个主要主题:

  • The quality of the code

    代码质量
  • Efficiency and robustness of the code

    代码的效率和健壮性
  • Are JS framework principles respected?

    是否遵守JS框架原则?
  • GitFlow principles

    GitFlow原理
  • Accessibility (a11y) and internationalization (i18n)

    可访问性(a11y)和国际化(i18n)

代码质量 (The Quality of the Code)

The quality level of source code is always difficult to evaluate, especially when it involves several files and, at a broader level, an entire application.

源代码的质量级别始终很难评估,尤其是当它涉及多个文件,更广泛地说,涉及整个应用程序时。

Anyway, good code must follow general software development principles, no matter the language. Here are some of them.

无论如何,良好的代码必须遵循通用的软件开发原则,无论使用哪种语言。 这里是其中的一些。

DRY和代码分解 (DRY and code factoring)

If we were asked for the first coding rule in software development that comes into our mind, we surely answer DRY, Don’t Repeat Yourself. It’s a key principle to avoid code redundancy.

如果我们被问到我们想到的软件开发中的第一个编码规则,我们肯定会回答DRY,不要重复自己。 这是避免代码冗余的关键原则。

Finding code duplication consists of inspecting the source code and spotting pieces of code that are repeated several times throughout a file or a bunch of files. It may take the form of a constant value, statements, or a set of static values.

查找代码重复项包括检查源代码并找出在一个文件或一堆文件中重复几次的代码段。 它可以采用常量值,语句或一组静态值的形式。

Then you can suggest to factor these lines of code with a new file containing static values or helpers/util functions that will be accessible anywhere in the project.

然后,您可以建议使用一个新文件将这些代码行分解为一个新文件,其中包含可在项目中的任何位置访问的静态值或辅助函数/实用函数。

Leveraging Javascript Framework’s techniques and features you use is a good habit. Whether you use Angular, React, or Vue.js, each one of them provides tools to factor pieces of code. You should check if a method can be reused as:

利用Javascript Framework的技术和功能是一个好习惯。 无论您使用Angular,React还是Vue.js,它们中的每一个都提供工具来分解代码段。 您应该检查方法是否可以按以下方式重用:

In addition, repeated templates can be extracted into a dedicated component or a fragment (if using React) to be reused as much as necessary. This follows the rule of component specialization from React.

此外,可以将重复的模板提取到专用组件或片段 (如果使用React)中,以根据需要进行重用。 这遵循了React的组件专门化规则。

有意义的评论 (Meaningful comments)

Clean code is self-explanatory.

干净的代码是不言自明的。

That is why clean code should not contain comments. Variable and method names should be super explicit. In such circumstances, reading code could be similar to reading a book — but that’s not always the case.

这就是为什么干净的代码不应包含注释。 变量名和方法名应该是超级明确的。 在这种情况下,阅读代码可能类似于阅读书本-并非总是如此。

Let’s be honest. Every project has its own specificities that should be commented. Meaningful comments are welcome to explain what is going on. But what is a meaningful comment?

说实话。 每个项目都有其自身的特点,应加以评论。 欢迎发表有意义的评论,以解释正在发生的事情。 但是什么是有意义的评论?

It should be written over two lines. The first one explains the situation (why do we do what we do). Then the second one indicates the action to face the issue. For example, let’s assume we have to authenticate automatically a user:

它应该写在两行上。 第一个解释了这种情况(为什么要做我们所做的事情)。 然后第二个指示指出要解决该问题的措施。 例如,假设我们必须自动认证用户:

// If a network error occurred because no cookie// Login again with JWT (JSON Web Token)if (err.message.includes('Missing Session token') && jwt) {  await loginUser(jwt);  doSomethingElse();}

Plus, seek for commented codes and suppress them! Indeed, it’s a common habit to comment a piece of code to activate it later or to avoid losing it. Frankly, it’s useful 10% of the time, so you can suggest erasing them without a doubt. If they are necessary later, you could refer to the Git history to retrieve the snippet. Deleting these comments will save you time when scrolling and will avoid irrelevant code in files.

另外,寻找注释的代码并压制它们! 确实,注释一段代码以稍后激活或避免丢失代码是一个普遍的习惯。 坦白地说,它在10%的时间内都是有用的,因此您可以毫无疑问地建议擦除它们。 如果以后需要使用它们,则可以参考Git历史记录来检索代码段。 删除这些注释将为您节省滚动时间,并避免文件中不相关的代码。

聪明的样式表 (A clever stylesheet)

CSS is not just a set of rules to give a color to a block of content or to lay out div in the DOM. It comes with some strategies that must be followed in every component of your project.

CSS不仅仅是一组为内容块添加颜色或在DOM中布置div的规则。 它带有一些必须在项目的每个组件中遵循的策略。

A clear CSS structure must be set in every template with explicit and meaningful class names. Check if stateful names are used, as an example:

必须在每个模板中使用明确且有意义的类名称设置清晰CSS结构。 例如,检查是否使用有状态名称:

<div class="phone-field--is-error">For input with error</div><div class="phone-field--is-success">For input with valid value</div>

New stylesheet languages such as Sass, Less, and Stylus allow you to create reusable CSS classes, thanks to classes’ combination, variables, and mixins. Using their superpowers will save you time and reduce efforts. Then checking for CSS improvements is a good bet to make reusable layout and appearance for components.

借助SassLessStylus等新的样式表语言,您可以创建可重用CSS类,这要归功于类的组合,变量和mixins。 利用他们的超能力将节省您的时间并减少工作量。 然后检查CSS的改进是使组件的布局和外观可重用的好选择。

Another potential check for a clever stylesheet concerns classes’ usage in the template. Indeed, using object syntax for CSS class definition may enhance code readability.

另一种可能的检查样式表的方法是,在模板中使用类。 实际上,将对象语法用于CSS类定义可以增强代码的可读性。

Here’s the documentation on object syntax for CSS class definition: Angular, React, Vue.js.

这是CSS类定义的对象语法文档: AngularReactVue.js

那单元测试呢? (What about unit tests?)

We will never stop saying it: A good piece of code is tested with unit tests.

我们永远不会停止这样说:一段好的代码已经通过单元测试进行了测试。

These unit tests check every branch the execution could run. It ensures a well-controlled code base and allows you to detect potential regressions quickly when introducing modifications.

这些单元测试检查执行可以运行的每个分支。 它确保代码库可控,并允许您在引入修改时快速检测潜在的回归。

Testing is a domain in its own right in computer science. Many key principles from software development should be applied to testing, such as DRY (seen earlier) and KISS (Keep It Stupid and Simple).

在计算机科学中,测试本身就是一个领域。 软件开发中的许多关键原则应应用于测试,例如DRY(较早见过)和KISS(保持愚蠢而简单)。

Unit test libraries like Jest, Mocha, Chai, and Jasmine provide plenty of methods to ease unit tests. If you want to extend your test battery with e2e (end-to-end) integration tests, Cypress, with a super friendly and intuitive GUI, is a good bet.

JestMochaChaiJasmine这样的单元测试库提供了许多简化单元测试的方法。 如果您想通过e2e(端到端)集成测试来扩展测试电池, 赛普拉斯具有超级友好和直观的GUI,是一个不错的选择。

A basic verification could be to check if a test setup or post-clean statements are not repeated several times. beforeEach and afterEach are appropriate methods to respectively prepare and post-clean the playground (provided by unit testing frameworks).

一个基本的验证可能是检查测试设置或清洗后声明是否没有重复几次。 beforeEachafterEach是分别准备和清理操场的适当方法(由单元测试框架提供)。

Test naming has also its importance. A good practice regarding naming is to select one of the following techniques, and stick to it:

测试命名也很重要。 有关命名的一个好的实践是选择以下技术之一并坚持使用:

it('SHOULD do something WHEN myVariable is true')# ORmyMethod_SHOULD_return_true_WHEN_myVariable_is_true()

守则的效率和稳健性 (Efficiency and Robustness of the Code)

Efficiency and robustness of the code are the main keys to getting a well-controlled and bug-free code base. It’s based on the coding habits and skills of developers, which come with experience.

代码的效率和健壮性是获得可控且无错误的代码库的主要关键。 它基于开发人员的编码习惯和技能,并附带经验。

处理意外值 (Handle unexpected values)

Even though you are 101% sure that a value will always be defined or have an expected value, this won’t be the case at some point in your project. Indeed, projects and applications evolve, and some unexpected values might appear.

即使您101%确信将始终定义值或具有期望值,但在项目中的某些时候情况并非如此。 实际上,项目和应用程序会不断发展,并且可能会出现一些意想不到的价值。

That is why it’s important to prevent these situations from happening by doing the following:

因此,通过执行以下操作来防止发生这些情况很重要:

  • Check for null or undefined values in object properties. If you’re using Typescript or Babel’s optional chaining, it’s super easy with ? syntax.

    检查对象属性中的nullundefined值。 如果您使用的是TypescriptBabel的可选链接 ,那么使用超级简单? 句法。

  • Ensure a default case is provided when using the switch-case statements to handle unexpected values.

    使用switch-case语句处理意外值时,请确保提供了default大小写。

  • Do the same as above for the if — else if — else conditional instructions.

    对于if — else if — else有条件的指令,请执行与上述相同的操作。

使条件语句清晰易读 (Make conditional statements clear and readable)

Efficient verification and a clear logic in the conditional instructions will help make for readable code.

有效的验证和条件指令中清晰的逻辑将有助于使代码更易读。

Then, ensure there is a rational and logical way in conditions. Maybe the verification is too complicated, maybe it’s not enough safe…

然后,确保条件中存在合理和逻辑的方式。 验证可能太复杂了,也许不够安全……

Suggest the creation of a dedicated method to make the condition more readable. Plus, it could be reused elsewhere.

建议创建专用方法以使条件更易读。 另外,它可以在其他地方重用。

分解组件 (Factorizing components)

It’s quite common to find similar templates in several components or in a single component template. A good practice is to extract this code into a specialized component or a reusable template.

在多个组件或单个组件模板中找到相似的模板是很常见的。 一个好的做法是将这些代码提取到专门的组件或可重用的模板中。

Angular provides ng-template or ng-container elements to create reusable templates.

Angular提供ng-templateng-container元素来创建可重复使用的模板。

React, by definition, is prone to create new specialized components. If you prefer reusable templates, you can find a way in the article “How to Build Reusable Layouts in React JS.”

根据定义,React倾向于创建新的专用组件。 如果您喜欢可重用模板,则可以在文章“ 如何在React JS中构建可重用布局 ”中找到一种方法。

Vue.js does not offer such things, but you could either create a dedicated component or follow the advice of Anthony Gore in his article “Extending Vue Component Templates.”

Vue.js不提供此类功能,但是您可以创建一个专用组件,也可以遵循Anthony Gore在他的文章“ 扩展Vue组件模板 ”中的建议。

是否遵守JS框架原则? (Are the JS Framework Principles Respected?)

JS frameworks are unavoidable now when it deals with creating dynamic and user-friendly web applications. They are a game changer in the front-end development world. Each framework comes with its own principles, rules, and conventions. Thus, you need to check if these standards are respected.

现在,JS框架在处理创建动态且用户友好的Web应用程序时不可避免。 他们是前端开发世界中的游戏规则改变者。 每个框架都有其自己的原理,规则和约定。 因此,您需要检查这些标准是否得到遵守。

命名约定 (Naming convention)

Naming conventions should be respected so that it allows identification of the content of the file’s or variable’s purpose.

应遵守命名约定,以便可以识别文件或变量用途的内容。

Here is a non-exhaustive list of checks for each framework:

这是每个框架检查的非详尽清单:

Angular (more details here)

Angular ( 更多详细信息在这里 )

  • filenames are suffixed with component, directive, filter, service or module

    文件名后缀有componentdirectivefilterservicemodule

  • Observable variables starts with a $

    可观察变量以$开头

  • private parameters in class constructor are prefixed with an underscore

    类构造函数中的私有参数以下划线为前缀

React (more details here and here)

React ( 此处此处有更多详细信息)

  • Use PascalCase for React components and camelCase for component instances

    将PascalCase用于React组件,将camelCase用于组件实例
  • Avoid using DOM component prop names for different purposes

    避免将DOM组件属性名称用于不同目的

Vue.js (more details here)

Vue.js ( 此处有更多详细信息 )

  • Component filename and name are “pascal-cased” (e.g., MyComponent.vue)

    组件的文件名和name是“用小写字母括起来的”(例如, MyComponent.vue )

  • Functions or variables from Vue instance starts with a $ (e.g., this.$route or this.$emit), therefore it’s a good practice not to add custom functions or variables starting with this character.

    Vue实例中的函数或变量以$开头(例如, this.$routethis.$emit ),因此,最好不要以此字符开头添加自定义函数或变量。

生命周期挂钩,数据流和访问器 (Lifecycle hooks, data flow, and accessors)

JS frameworks are built according to several lifecycle hooks that rule the component state and behaviour. They need to be used appropriately to avoid unexpected infinite loops or memory leaks.

JS框架是根据几个生命周期挂钩构建的,这些挂钩决定了组件的状态和行为。 需要适当使用它们以避免意外的无限循环或内存泄漏。

For example, in Angular, you need to check when using Subscriptions if the beforeDestroy lifecycle hook is unsubscribing all subscriptions by calling the unsubscribe method.

例如,在Angular中,您需要在使用“ Subscriptions时检查beforeDestroy生命周期挂钩是否通过调用unsubscribe方法取消订阅所有订阅。

In Vue.js, the beforeRouteEnter guard (or any route guards) should, in the end, call the next method to navigate through. This concerns Angular guards too.

在Vue.js中, beforeRouteEnter保护(或任何路由保护)最后应调用next方法进行导航。 这也与Angular守卫有关。

In React, you should check for the usage of componentWillMount and componentWillUpdate lifecycle methods, which are now deprecated because of misunderstanding.

在React中,您应该检查componentWillMountcomponentWillUpdate生命周期方法的使用情况,由于误解,这些方法现在已过时

render method is mandatory in a class component. It mustn’t modify component state. Further details may be found here.

render方法在类组件中是必需的。 它不能修改组件状态。 可以在此处找到更多详细信息

In Vue.js again, you should check for data property changes in computed, which is a main anti-pattern practice. Computed properties are just meant to be data accessors and not to update values. This could be applied to Angular getters.

在Vue.js再次,你应该检查data的属性更改computed ,这是一个主要的反模式的实践。 计算属性仅是作为数据访问器,而不是更新值。 这可以应用于Angular getters

GitFlow原理 (GitFlow Principles)

If you are not familiar with this term, the GitFlow means the strategy you have set to manage several versions of the same code base. There is a reference branch and many copies of it with their specificities.

如果您不熟悉此术语,则GitFlow表示您已设置用于管理同一代码库的多个版本的策略。 有一个参考分支,并且有很多分支及其特殊性。

Common rules must be applied regarding this strategy and must be followed to avoid code loss or conflicts. The GitFlow must be respected in every code review.

必须对此策略应用通用规则,并且必须遵循这些规则以避免代码丢失或冲突。 在每次代码审查中都必须尊重GitFlow。

每次提交都不应破坏应用程序 (Every commit shouldn’t break the app)

This is more advice than a check for the code review. Indeed, every single commit mustn’t introduce building time or runtime errors.

这比检查代码检查更多的建议。 实际上,每个提交都不得引入构建时间或运行时错误。

If for any reason you need to roll back to a specific commit and this one fires troubleshoots, it will put a mess in all the source code.

如果出于某种原因您需要回滚到特定的提交并且此操作引发了故障排除,则会使所有源代码陷入混乱。

That is why it’s a better way to commit frequently with tiny but controlled and clear changes.

这就是为什么这是一种更好的方法,可以频繁地进行微小但可控且清晰的更改。

检查涉及的分支 (Check the involved branches)

It’s not a surprise that a merge request involves two branches: the one containing changes and the reference branch.

合并请求涉及两个分支也就不足为奇了:一个分支包含更改和引用分支。

It’s a good idea to check both of them. Indeed, as we have no restriction on creating branches, a mistake might be easily introduced. This may come from various reasons:

最好将它们都检查一下。 实际上,由于我们对创建分支没​​有任何限制,因此很容易引入错误。 这可能来自多种原因:

  • wrong reference branch (for example, if there is a sub-branch)

    错误的参考分支(例如,如果有子分支)
  • spelling error

    拼写错误
  • duplicated branch to merge (if a copy of the branch to merge has been created for any reason)

    要合并的分支重复(如果出于任何原因创建了要合并的分支的副本)

Two good practices to avoid introducing unwanted pieces of code are:

避免引入不需要的代码段的两种良好做法是:

  • Name the feature branch explicitly by prefixing a ticket number (if you use a ticketing platform such as GitLab, GitHub, JIRA, or Azure DevOps Services)

    通过添加票证编号来明确命名功能分支(如果使用票务平台,如GitLabGitHubJIRAAzure DevOps Services )

    Example:

    例:

    287-add-tracking

    287-add-tracking

  • Merge your reference branch into the branch to merge first. This will help to detect potential errors and conflicts in the local branch. Thus, the reference branch is protected and the merge will be controlled.

    将您的参考分支合并到该分支中以首先进行合并。 这将有助于检测本地分支中的潜在错误和冲突。 因此,参考分支受到保护,合并将受到控制。

在本地测试分支 (Test the branch locally)

This is a zealous practice but it should be a reflex. Testing the branch locally by checking it out is a nice-to-have habit.

这是一种热情的做法,但应该是一种反思。 通过检出本地测试分支是一个好习惯。

Using the simple command git checkout my-feature-branch-to-test and running the app will allow you to detect errors locally when building the app. Of course, it will be a handy way to verify if the specifications have been fulfilled.

使用简单的命令git checkout my-feature-branch-to-test并运行应用程序,可以使您在构建应用程序时在本地检测错误。 当然,这将是验证规格是否已满足的便捷方法。

Yet let’s be honest: This costs time, and in a world in which time-to-market must be as short as possible, this practice is often dropped out.

但说实话:这会浪费时间,而且在这个产品上市时间必须尽可能短的情况下,这种做法经常会被放弃。

可访问性(a11y)和国际化(i18n) (Accessibility (a11y) and Internationalization (i18n))

Think broadly! A web app may be visited by a large part of the population, including people from all over the world. Including people with visual, motor, and other impairments by adding a few attributes in your code will change the experience you provide them.

广泛考虑! Web应用程序可能会被包括世界各地的人在内的大部分人访问。 通过在代码中添加一些属性来包括视觉,运动和其他功能障碍的人,将会改变您为他们提供的体验。

Accessibility (a11y) and internationalization (i18n) have become key concepts in front-end development. If these features don’t ring a bell with you, you can refer to my previous article “The Front-End Features You Might Have Missed,” User Experience section.

可访问性(a11y)和国际化(i18n)已成为前端开发中的关键概念。 如果您不满意这些功能,可以参考我以前的文章“ 您可能会错过的前端功能” ,“用户体验”部分。

辅助功能属性 (Accessibility attributes)

You should ensure the presence of a11y attributes such as:

您应确保存在以下所有属性:

i18n键 (i18n keys)

A single commit involves many perspectives (including HTML templating, CSS styling, testing, and components), and forgetting a translation may occur — especially when you manage several languages.

一次提交涉及多个角度(包括HTML模板,CSS样式,测试和组件),并且可能会忘记翻译-尤其是当您管理多种语言时。

Therefore, do not forget to check if each translation has its match for each language. Plus, a translation may be used in a template but does not correspond to an existing key.

因此,不要忘记检查每种翻译是否与每种语言相匹配。 另外,翻译可以在模板中使用,但不对应于现有键。

It seems a boring task, but the devil hides in the details, does it?

这似乎很无聊,但是魔鬼隐藏在细节中,对吗?

利用您使用的i18n库 (Leverage the i18n library you use)

You can do incredible things with your i18n library.

您可以使用i18n库执行令人难以置信的事情。

They are getting more and more polyvalent and provide powerful functionalities. You can handle:

它们越来越多价并提供强大的功能。 您可以处理:

  • Pluralization

    多元化
  • Date and number formatting

    日期和数字格式
  • HTML templating

    HTML模板
  • Translations lazy loading

    翻译延迟加载

Do not hesitate to over-use it, especially about conjugation (be, is, are, was, were, been), or to add a CSS class on a particular word of a sentence. The goal is to make your translations as much reusable as possible.

不要犹豫,过度使用它,特别是关于结合( 一直 ),或者对一个句子的特定单词添加CSS类。 目的是使您的翻译尽可能地可重用。

Leveraging a i18n library will save you time and effort. It’s worth it instead of reinventing the wheel!

利用i18n库可以节省您的时间和精力。 值得而不是重新发明轮子!

结论 (To Conclude)

Reviewing merge requests may take a lot of time, but it’s a good practice to get used to. It allows you to get informed of changes other developers introduce to the code base. In addition, it’s a different way to share programming language tricks, front-end development insights, and experiences.

审核合并请求可能会花费很多时间,但这是习惯的好习惯。 它使您可以了解其他开发人员对代码库所做的更改。 此外,这是共享编程语言技巧,前端开发见解和经验的另一种方式。

In the end, the time spent in reviewing will be a good bet for the future since the earlier you set good coding practices, the earlier time spent to review will be shortened. It’s an investment in the future… in some ways.

最后,花在审查上的时间将是未来的好选择,因为您越早设置好的编码实践,就可以缩短花在审查上的时间越早。 在某些方面,这是对未来的投资。

翻译自: https://medium.com/better-programming/what-you-should-inspect-in-a-front-end-code-review-4010e1bc285a

前端代码审查工具

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/429194?site
推荐阅读
相关标签
  

闽ICP备14008679号