On team projects, good coding habits are very important. Here are some code habits from my own development projects that might help you

WHY?

  • A team project is not a person writing code, writing code by yourself is fun, but also let others see clearly
  • Reduce bug processing, convenient bug search and solution, improve development efficiency, reduce unnecessary energy consumption
  • Convenient for later maintenance

HOW?

The basic principles

  • Code indentation is strictly uniform, or both2Spaces, or both4Space, prohibit all space cross use lead to code alignment, look at the headache situation
  • Disallow code breaks (extra blank lines within a complete code block)
  • Comments must be written
  • Non-engineering projectscssA ban onhtmlWrite in code
  • Delete code that is useless for logging out
  • Easy to develop code, for exampleconsole.log()oralert()Delete them after development

HTML

  • Write a comment

If you have a small amount of code, it’s easy to read, but if you have a large amount of code, it’s not easy to read a lot of uncommented code, so comments should be written

<! -- yes -->
<! -- Next step
<div class="btn-group df-jcc">
  <button class="next-step cp">The next step</button>
  <button class="submit cp">submit</button>
  <button class="exit cp">exit</button>
</div>

<! - tip - >
<div class="prompt-layer">
  <div class="title df-aic df-jcc">
    <h3>Warm prompt</h3>
  </div>
  <div class="prompt-content">
    <img src="xxx.png" alt="xxx">
    <p class="ac"></p>
  </div>
</div>


<! -- no -->
<div class="btn-group df-jcc">
  <button class="next-step cp">The next step</button>
  <button class="submit cp">submit</button>
  <button class="exit cp">exit</button>
</div>
<div class="prompt-layer">
  <div class="title df-aic df-jcc">
    <h3>Warm prompt</h3>
  </div>
  <div class="prompt-content">
    <img src="xxx.png" alt="xxx">
    <p class="ac"></p>
  </div>
</div>
Copy the code
  • Reasonable use of labels
<! - the head -- -- >
<header></header>
<! -- Main content -->
<main></main>
<! - the tail -- -- >
<footer></footer>
<! - button - >
<button></button>
<! Navigation -- - >
<nav></nav>
<! -- Title H1-H6 -->
<h3></h3>.Copy the code
<! -- yes -->
<button class="btn"></button>

<! -- no -->
<div class="btn"></div>
Copy the code
  • The labelclassoridNomenclature semantics

Head: class = “header”

Tail: footer

Navigation: nav

Sidebar: sidebar

TAB page: TAB

Menu: a menu

.

<! -- yes -->
<div class="sidebar"></div>

<! -- no -->
<div class="left"></div>
Copy the code
  • Tag attribute value used""Packages, do not use' '
<! -- yes -->
<footer class="footer"></footer>

<! -- no -->
<footer class='footer'></footer>
Copy the code
  • Write order of label attributes

class

id

data-*

src, type, href, value

title, alt

<! -- yes -->
<a class="" id="" data-val="" href=""></a>

<! -- no -->
<a id="" href="" class="" data-val=""></a>
Copy the code
  • Disallow code faults. extra blank lines make code very readable
<! -- yes -->
<div class="point-type df bg-white mb-20 p-20-30 border-e5">
  <div class="text-title">
    <h3></h3>
  </div>
  <nav class="flex-1">
    <ul class="clearfix"></ul>
  </nav>
</div>

<! -- very poor -->
<div class="point-type df bg-white mb-20 p-20-30 border-e5">

  <div class="text-title">
  
    <h3></h3>
  </div>
  
  <nav class="flex-1">
    <ul class="clearfix"></ul>
    
  </nav>
</div>
Copy the code

CSS

  • Project initialization stylereset.css
*{-webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; } body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,code,form,fieldset,legend,input,button,textarea,p,blockquote,th,td { margin:0; padding:0; } body {color: rgba (51,51,51,0.8); font-size:14px; Font-family: Arial,"Microsoft YaHei"," black ","宋体",sans-serif; } td,th,caption { font-size:14px; } h1, h2, h3, h4, h5, h6 { font-weight:normal; font-size:100%; } address, caption, cite, code, dfn, em, strong, th, var { font-style:normal; font-weight:normal; } a { color:#555; text-decoration:none; } a:hover { text-decoration: none; } img { border:none; vertical-align: middle} ol,ul,li { list-style:none; } i{font-style: normal; } input, textarea, select, button {font:14px "Arial","Microsoft YaHei"," 宋体",sans-serif; } input,button{border: none; outline: none; } input[type=checkbox], input[type=radio]{margin: 0; } table { border-collapse:collapse; } html {overflow-y: scroll; } p{margin: 0; } .clearfix:after {content: "."; display: block; height:0; clear:both; visibility: hidden; } .clearfix { *zoom:1; }/* Public class */Copy the code
  • Project custom common styles are unified in a given CSS (based on my own habits, here are my CSS habits)
  1. Unify some commonly used stylespublic.cssAvoid duplicate writing in documents
/* * public.css */
 
.fl {
    float: left;
}
.fr {
    float: right;
}
.ac {
    text-align: center;
}
.ar {
    text-align: right;
}
.df {
    display: -webkit-flex;
    display: flex;
}
.df-aic {
    display: -webkit-flex;
    display: flex;
    align-items: center;
}
.df-jcc {
    display: -webkit-flex;
    display: flex;
    justify-content: center;
}
.flex-1 {
    flex: 1;
}
.bs {
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}
.cp {
    cursor: pointer;
}
.bg-white {
    background-color: #fff;
}
.w100 {
    width: 100%;
}
.h100 {
    height: 100%;
}
.mb-20 {
    margin-bottom: 20px; }...Copy the code
  1. Other common styles are put togetherbase.cssIn the
/* * base.css * All styles that can be used by multiple pages at the same time are put into this file */
 
body {
    background-color: #f9f9fb;
}
.container {
    width: 1280px;
    margin: auto;
    padding: 0 15px;
}

/ * * / head
header {}

/* Main content */
main {}

/ * * / tail
footer {}

Search / * * /
.search {}

/* checkbox */
input[type="checkbox"] {
    width: 20px;
    height: 20px;
    -webkit-appearance:none;
    background: url("xxx.png") no-repeat center;
}
input[type="checkbox"]:checked {
    background: url("xxx.png") no-repeat center; }...Copy the code
  • Write a comment

Comment on the style of a block code, such as header, footer, list, search, return to top…

/* yes */
/* header */
header {}

/* footer */
footer {}

/* Return to top */
.go-top {}

/* no */
header {}
footer {}
.go-top {}
Copy the code
  • cssWritten order
  1. Text position styleFloat, position, left, top, display, Z-index...
  2. Text width, height, marginWidth, height, padding, margin...
  3. Text content color, sizeColor, text-align, text-align...
  4. Text background, borderBackground and border...
  5. otherBorder-radius, transform, transiton...
/* yes */
nav ul li {
    float: left;
    width: 90px;
    height: 32px;
    margin: 10px;
    padding: 0 20px 0 10px;
    font-size: 18px;
    text-align: right;
    border: 1px solid #eee;
    border-radius: 4px;
}

/* no */
nav ul li {
    margin: 10px;
    text-align: right;
    border: 1px solid #eee;
    width: 90px;
    height: 32px;
    padding: 0 20px 0 10px;
    float: left;
    font-size: 18px;
    border-radius: 4px;
}
Copy the code
  • padding marginwriting
/* Only one value */
.title {
    margin-left: 10px;
}

/* Multi-value case */
/* yes */
.title {
    margin: 0 20px 10px;
}

/* no */
.title {
    margin-top: 0;
    margin-right: 20px;
    margin-left: 20px;
    margin-bottom: 10px;
}
Copy the code
  • cssLeave a space on each side of the selector
/* yes */
label + input {
    margin-left: 10px;
}
nav > ul > li {
    margin-left: 10px;
}

/* no */
label+input {
    margin-left: 10px;
}
nav>ul>li {
    margin-left: 10px;
}
Copy the code

JavaScript

  • Write a comment
  1. Comments for the whole function module

    /** * list filter * @param {Array} XXXXX saves the selected province * @param {String} XXXXXXXXXX saves the selected year * @method XXXX saves the selected part, Used to filter * @method XXXX deletes the condition selected in the filter *...... * /
    Copy the code
  2. Whole function module internal small function code comment also needs to write

    // List paging
    xxxx
    
    // Reset the filter criteria
    xxxx
    Copy the code
  • Hump named
/* yes */
let searchVal = ' ';
function getUserInfo() {}

/* no */
let searchval = ' ';
function getuserinfo() {}...Copy the code
  • Add Spaces to make your code more elegant
  1. === === > < % + * /,…

    /* yes */
    const name = 'yuci';
    const userArr = ['a'.'b'.'c'];
    if (i === 0) {
        // do
    }
    for (let i = 0, len = arr.length; i < len; i++) {
        // do
    }
    
    /* no */
    const name='yuci';
    const userArr=['a'.'b'.'c'];
    if(i===0) {// do
    }
    for(let i=0,len=arr.length; i<len; i++){// do}...Copy the code
  2. if else for while switch try catch function

    /* yes */
    if (i === 0) {
        // do
    } else {
        // do
    }
    try {
        // do
    } catch {
        // do
    }
    switch (dataSort) {
        // do
    }
    for (let i = 0, len = arr.length; i < len; i++) {
        // do
    }
    const fn = username= > {
        // do
    }
    function fn() {
        // do
    }
    
    /* no */
    if(i===0) {// do
    }else{
        // do
    }
    for(let i=0,len=arr.length; i<len; i++){// do
    }
    switch(dataSort){
        // do
    }
    const fn=username= >{
        // do
    }
    function fn(){
        // do}...Copy the code
  3. Object: Add a space to the right

    /* yes */
    const user = {
        name: 'xxx'.age: 'xxx'
    }
    this.state = {
        username: ' '
    }
    this.setState({
        username: 'yucihent'
    })
    
    /* no */
    const user = {
        name:'xxx'.age:'xxx'}...Copy the code
  • Disallow code faults (very poor readability)
/* yes */
/** * fetch requests encapsulate */
let fetchData = async (url, method, data) => {
    let options;
    let dataStr = ' ';
    const headers = {
      'Accept': 'application/json'.'Content-Type': 'application/x-www-form-urlencoded'
    };
    / / get request
    if (method === 'get') {
        if (typeof data === 'object') {
            Object.keys(data).forEach(key= > {
                dataStr += `${key}=${data[key]}& `
            });
            if (dataStr) {
                dataStr = dataStr.substring(0, dataStr.length - 1)}; url =`${url}?${dataStr}`;
        }
        options = {
            method: 'GET',
            headers,
        }
    } else {
        let formData = new FormData();
        for (let key in data) {
            formData.append(key, data[key])
        }
        options = {
            method: 'POST'.body: formData
        }
    }
    let response = await fetch(url, options);
    let res = await response.json();
    return res;
}

/* very poor very poor very poor */
let fetchData = async (url, method, data) => {
    let options;
    let dataStr = ' ';
    const headers = {
      'Accept': 'application/json'.'Content-Type': 'application/x-www-form-urlencoded'
    };
    / / get request
    if (method === 'get') {
        if (typeof data === 'object') {
            Object.keys(data).forEach(key= > {
                dataStr += `${key}=${data[key]}& `
            });
            
            if (dataStr) {
                dataStr = dataStr.substring(0, dataStr.length - 1)}; url =`${url}?${dataStr}`;

        }
        options = {
            method: 'GET',
            headers,
        }
    } else {
        let formData = new FormData();
        
        for (let key in data) {
            formData.append(key, data[key])
            
        }
        options = {
            method: 'POST'.body: formData
        }


    }
    
    let response = await fetch(url, options);
    let res = await response.json();
    return res;


}
Copy the code
  • Don’t have too many lines of code
/* yes */
import {
    List,
    InputItem,
    WingBlank,
    WhiteSpace,
    Button,
    Radio,
    Toast
} from 'antd-mobile'

/* no */
import { List, InputItem, WingBlank, WhiteSpace, Button, Radio, Toast } from 'antd-mobile'
Copy the code
  • use' 'Rather than""
/* yes */
import HelloWorld from './components/HelloWorld'
methods: {
    delItem(index) {
    	this.$emit('delItem', index)
    }
}

/* no */
import HelloWorld from "./components/HelloWorld"
methods: {
    delItem(index) {
    	this.$emit("delItem", index)
    }
}
Copy the code
  • Concise and clear
  1. Template string substitution ++ string concatenation

  2. Deconstruction assignment

    /* yes */
    this.state = {
        name: 'xxx'.age: 'xxx'
    }
    const { name, age } = this.state;
    
    /* no */
    const name = this.state.name;
    const age = this.state.age;
    Copy the code
  3. Attribute Name Short for attribute value

    /* yes */
    components: {
        Header,
        Footer
    }
    
    /* no */
    components: {
        Header: Header,
        Footer: Footer
    }
    Copy the code
  4. function

    /* yes */
    methods: {
        delItem(index) {
        	this.$emit('delItem', index)
        }
    }
    
    /* no */
    methods: {
        delItem: function(index) {
        	this.$emit('delItem', index)
        }
    }
    Copy the code

    .

conclusion

The above is a summary of some of the code specification problems I encountered in the project and my coding habits. It is not suitable for every developer, but most of the coding styles should be popular and I hope it can help you

say

The golden rule of teamwork: Your code is viewed as your own, and good coding habits are very, very important