Specification: front-end code development specification

1. Front-end static code checking tool

1.1. ESLint: ESLint is a plug-in JavaScript code inspection tool that can use rule plug-ins or custom rules to perform static inspection on the code.

1.2, JSLint: JSLint is a very popular JavaScript code inspection tool developed by Douglas Crockford, which can help developers check potential problems in the code.

1.3. JSHint: JSHint is a branch of JSLint, which supports more flexible configuration options and provides more friendly error messages.

1.4, TSLint: It is a TypeScript code quality tool, similar to ESLint, which supports custom rules and plug-ins.

1.5. Prettier: It is a code formatting tool that supports multiple languages ​​and editors, and can automatically format the code to make the code style uniform.

1.6. Stylelint: Stylelint is a static inspection tool specially used for CSS, which can check whether the CSS code conforms to certain specifications and styles.

1.7, TypeScript: TypeScript is an open source programming language that can be used to develop large and complex JavaScript applications. It provides features such as type checking, static analysis, and code hints to help developers write more robust and maintainable code.

The above tools can help check code quality, improve code maintainability and readability, it is recommended to choose the appropriate tool according to project requirements.

2. The following are some common front-end code review specifications

2.1. Code format: The code should be formatted according to a certain format to improve readability and maintainability. For example, use spaces to align code, use indentation to indicate code blocks, and so on.

2.2. Variable naming: Variables, function names, constants, etc. should be meaningful, clear and easy to understand, and consistent with the actual meaning they represent.

2.3. Comment specification: Comments should be appropriately added to the code. The comments should be clear and clear, covering the key information of the code, and should not be too much or too little.

2.4. Testing and error handling: The code should have sufficient error handling mechanisms, and it should also be equipped with corresponding test cases to ensure code quality.

2.5. Performance optimization: Code should be optimized to minimize resource usage and load time. For example, avoid redundant code, reduce file size, improve parallelism during loading, and so on.

The above are just some common front-end code review specifications. You can also refer to various front-end frameworks, languages, design patterns and other related documents to formulate matching review specifications in your project.

3. The naming rules of JavaScript variables are as follows

3.1. Variable names must start with a letter, an underscore (_) or a dollar sign ($).

3.2. Variable names can contain letters, numbers, underscores or dollar signs.

3.3. Variable names should not use JavaScript reserved words, such as if, else, for, function, etc.

3.4. Variable names should use meaningful names to make the code easy to understand and maintain.

3.5. Variable names should be named in camel case, that is, the first word is lowercase, and the first letter of the following words is capitalized (for example: firstName).

let userName;
let num1;
let totalAmount;
let _privateValue;
let $globalVar;

Fourth, JavaScript avoids redundant variable names

4.1. Use meaningful variable names: Use meaningful variable names to avoid redundant variable names.
For example:
use "userName" instead of "name" to store user names.
Use const user = { name: "snow" }, don't use const user = { userName: "snow" }, when using this object, it is directly user.name instead of user.userName.

4.2. Avoid global variables: Using global variables may lead to variable name conflicts and redundancy. You can avoid using global variables in your code and instead confine variables to functions or modules.

4.3. Using scope: In JavaScript, each function has its own scope. Scoping can be used to avoid variable name redundancy. For example, a variable declared within a function can only be accessed within that function, which avoids variable name conflicts and redundancy.

4.4. Use const and let: Use const and let to avoid redundant variable names. const and let limit the scope of variables and provide better code safety and maintainability.

4.5. Use naming conventions: Using naming conventions in code can avoid redundant variable names. For example, you can use camel case or underscore nomenclature, etc.

Through the above methods, the redundancy and conflict of variable names in JavaScript can be effectively avoided, and the code quality and maintainability can be improved.

5. CSS naming convention BEM

BEM is a commonly used CSS naming convention. Its full name is Block, Element and Modifier.

5.1. Block: A block is an independent, reusable component that contains one or more elements. It is recommended to use a single letter or word for the class name of the block, and use a hyphen (-) to connect multiple words, for example: .menu, .list.

5.2, Element (Element): An element is a component of a block, it can only belong to a block, and cannot be used alone. The class name of the element should be composed of the class name of the block and a single letter, a single word or words, and multiple words are also connected with a hyphen (-), for example: .menu__item, .list__item.

5.3, Modifier (Modifier): Modifiers are used to enhance the characteristics of blocks or elements, and can also be used to express status, themes, etc. A modifier's class name should consist of the block or element's class name and a single word or words, joined by a hyphen (-), eg: .menu__item--active, .list__item--disabled.

Using BEM naming conventions can make CSS code more readable and maintainable. At the same time, it can also reduce unnecessary style conflicts and improve component reusability.

6. In addition to the BEM naming convention, there are some common CSS naming conventions as follows

6.1. OOCSS (Object-Oriented CSS): This is an object-oriented CSS design method, which treats UI modules as independent objects and decomposes styles into two parts, structure and skin. Structural styles are usually defined in class names, while skin styles are defined in suffixed class names, for example: .button, .button-red.

6.2. SMACSS (Scalable and Modular Architecture for CSS): This is a scalable and modular CSS architecture that decomposes style sheets into five levels: foundation, layout, module, state, and theme. Each level has a corresponding naming convention and organization.

6.3. ACSS (Atomic CSS): This is an atomic class-based CSS design method, which defines styles as a single attribute and value pair, and each attribute and value pair corresponds to an atomic class. This approach can greatly reduce the duplication and redundancy of styles, and improve the maintainability of style sheets.

6.4, CSS Modules: This is a method of modularizing and componentizing CSS, which treats style sheets as independent modules, each with its own namespace and local scope, to prevent style conflicts and improve component of reusability.

Different naming conventions are suitable for different projects and teams. Choosing a naming convention that suits you can improve the maintainability and reusability of CSS code.

7. Suggestions on JavaScript Naming Semantics

In JavaScript, naming semantics usually refers to the encoding method of variable names, function names, class names and other symbolic names that are clear, easy to understand, and express meaning and purpose. Here are some suggestions for naming semantics:

7.1. Variable name: The variable name should accurately describe the content stored in the variable, and abbreviations or abbreviations should be avoided unless the abbreviation or abbreviation is widely accepted. For example, using `fruit` for fruit and `price` for price should not be used  usrNm to represent a username, but should be used  userName.

7.2. Function name: The function name should accurately describe the purpose and function of the function. The camel case nomenclature starting with a lowercase letter and the form of verb plus noun are easier to understand. For example, use `calculateTotal` to calculate the total amount, use `displayMessage` to display messages, getUserNameget usernames, validateEmailverify email addresses, etc.

7.3. Class name: The class name should accurately describe the purpose and function of the class. For example, use `Person` to represent a human being, `Car` to represent a vehicle, etc.

7.4. Constant name: The constant name should be composed of uppercase letters and underscores, and describe the purpose and meaning of the constant. For example, use `MAX_WIDTH` for maximum width, `PI` for pi, etc.

7.5. Enumeration value: The enumeration value should be composed of uppercase letters and underscores, and describe the purpose and meaning of the enumeration value. For example, use `COLOR_RED` for red, `SIZE_LARGE` for large, etc.

7.6. Boolean value: If a variable has only two values, ie true and false, it should be named with an adjective or the past participle of the verb. For example, use `isVisible` to indicate whether it is visible, use `isDone` to indicate whether it is done, etc.

7.7. Callback function name: The callback function name should accurately describe the function and purpose of the callback function. For example, use `onSuccess` to represent the callback function executed when the operation is successful, use `onError` to represent the callback function executed when the operation fails, etc.

7.8. The class name should use the camel case naming method starting with a capital letter, which can describe the meaning represented by the class. For example, a class representing a user should be named  User, and a class representing an item should be named  Product.

By naming semantics, the code can be easier to understand and maintain, and the readability and maintainability of the code can be improved.

Eight, js saves the attribute value of the object as a local variable 

const person = {
  name: 'John',
  age: 30,
  gender: 'male'
};

//推荐
const { name, age, gender } = person;
console.log(name, age, gender);

//不推荐
console.log(person.name, person.age, person.gender);

Nine, the minimum function criterion

The Minimum Function Principle (Single Responsibility Principle, SRP) means that when writing a function, the responsibility of the function should be guaranteed to be single, that is, each function should only do one thing. This makes functions cleaner, more readable, and easier to maintain and test. SRP is one of the foundational principles of object-oriented programming.

Following the SRP can have the following benefits:

1. Improve the readability and maintainability of the code: each function is responsible for only one responsibility, the code logic is clearer, and it is easy to understand and modify.
2. Improve the testability of the code: each function has only one responsibility, and more precise test cases can be written to make the code more robust and stable.
3. Improve code reusability: Functions with a single responsibility can be reused in different scenarios, avoiding redundant functions and code duplication.
4. Better modularization and encapsulation: Functions with similar responsibilities can be combined into a module or class to improve code reusability and maintainability.

In actual programming, there are many ways to follow SRP, such as:

1. Each function handles only one parameter, not multiple parameters.
2. Each function returns only one value or modifies only one value.
3. Split a function into multiple functions, and each function is only responsible for a specific responsibility.
4. Split a function into multiple steps, each step responsible for only one responsibility, and then combine these steps into a function.

10. It is recommended to use functional programming

Here's a simple JavaScript functional programming example that takes another function as an argument, applies that function to each element of the array, and returns the resulting array:

function mapArray(array, f) {
  var result = [];
  for (var i = 0; i < array.length; i++) {
    result.push(f(array[i]));
  }
  return result;
}

// 定义一个函数,计算一个数的平方
function square(x) {
  return x * x;
}

var numbers = [1, 2, 3, 4, 5];
// 使用函数式编程,将 square 函数应用到 numbers 数组的每个元素中
var squares = mapArray(numbers, square);
console.log(squares); // [1, 4, 9, 16, 25]

In this example, we define a function  mapArray()that takes an array and a function as arguments, applies the function to each element of the array, stores the result in a new array, and returns the new array. We also define a function  square()that calculates the square of a number. We then   store the square of each element in the array in  an array using mapArray() function and  square() function   and   output the array to the console using  function  .numberssquaresconsole.log()squares

11. Vue project development specification

11.1, code style

Use eslint in the Vue project to ensure a unified code style. For specific settings, please refer to  the official eslint-config-vue document

11.2. Directory structure

The directory structure of a Vue project should be clear to facilitate code organization and maintenance.

11.2.1. Basic directory structure

|-- dist                               // 打包后的文件目录
|-- public                             // 公共静态资源文件,如index.html
|   |-- index.html
|-- src                                // 源码目录
|   |-- api                            // 接口请求相关文件
|   |   |-- index.js                   // 请求封装入口文件
|   |   |-- api.js                     // 接口具体实现文件
|   |   |-- ...                        // 其他接口实现文件
|   |-- assets                         // 图片,字体等静态资源文件
|   |-- components                     // 公共组件目录
|   |-- mixins                         // 公共 mixins
|   |-- router                         // 路由文件
|   |-- store                          // Vuex 状态管理文件
|   |-- utils                          // 公共工具函数
|   |-- views                          // 页面组件目录
|   |-- App.vue                        // 根组件
|   |-- main.js                        // 入口文件
|-- .gitignore                         // git 忽略文件
|-- babel.config.js                    // babel 配置文件
|-- package.json                       // 依赖配置文件
|-- README.md                          // 项目说明文件
|-- vue.config.js                      // Vue 配置文件

11.2.2. Component directory structure

|-- components
|   |-- Login
|   |   |-- index.js                   // 组件入口文件
|   |   |-- Login.vue                  // 组件代码文件
|   |   |-- Login.scss                 // 组件样式文件
|   |   |-- Login.spec.js              // 组件测试文件
|   |   |-- Login.story.js             // 组件故事文件

11.3. Component naming

The naming of Vue components should be meaningful so that others can understand and use the code.

Naming rules:

  • all lowercase words
  • Use a hyphen (-) between multiple words
  • It is recommended to use the same prefix for components with similar functions, such as  v-buttonv-button-group

Avoid abbreviations in vue component names, e.g. use  buttoninstead of  btn.

11.4. Component structure

The structure of Vue components should be clear, easy to reuse and maintain.

The code structure of the vue component is suggested as follows:

<template>
  <div class="container">
    <!-- 组件主体内容 -->
  </div>
</template>

<script>
  export default {
    name: 'ComponentName', // vue 组件名称

    props: { // vue 组件属性
      propA: {
        type: String,
        default: 'A'
      },
      propB: {
        type: Number,
        default: 0
      }
    },

    data () {
      return {} // vue 组件数据
    },

    computed: { // vue 计算属性
      computedA () {
        // ...
      }
    },

    watch: { // vue 监听器
      'watchA' (val, oldVal) {
        // ...
      }
    },

    methods: { // vue 组件方法
      methodA () {
        // ...
      }
    },

    // vue 生命周期
    beforeCreate () {},
    created () {},
    beforeMount () {},
    mounted () {},
    beforeUpdate () {},
    updated () {},
    beforeDestroy () {},
    destroyed () {}
  }
</script>

<style lang="scss" scoped>
  .container {
    /* 样式代码 */
  }
</style>

11.5, code comments

Code comments are very important for maintainability and readability. It is recommended to make comments in the code to facilitate others to understand and modify the code.

Annotation rules:

  • Blank lines are left between comments to distinguish different sections
  • The content of the comment should be concise and clear, and should not be too long
  • Place comment content above the commented code instead of to the right
  • If you can understand it through the standard naming, you don’t need to write comments

11.6. Others

  • Component styles are uniformly written using SCSS
  • It is forbidden to use  v-if and  v-for use in combination, because this will affect performance, it is recommended to use the method of computing properties
  • Variable names, function names, file names, etc. should be named meaningfully, and do not use single-character naming methods, such as  ab
  • When using Vuex state management, it is recommended that a single file should not exceed 400 lines of code

12. This article is created with the help of AI, welcome to exchange and correct me, follow me, and learn together

reference link

Front-end team code review CheckList checklist - Nuggets

Recommend several code specification document libraries, it is recommended to collect! - Nuggets

Front-end code review specification - short book

Guess you like

Origin blog.csdn.net/snowball_li/article/details/124928488