The length may be quite long, but I feel that a set of specifications is actually very important for a team, which will also be convenient to maintain. If the following specifications feel helpful to your team, I hope to put them into practice in the team or recommend them to your leader. The code specifications are as follows: Tencent AlloyTeam, I hope you can follow a look, take what you need.

A subsequent article I also supplement is complete, a total of two, is practical, is a set of the front end of the development of normative eslint, another is a hand to touch the hand take you practice the front end of the development standard, hope you can go to have a look at, and then put the standard practice, there are fewer bugs in the development of their own.

If possible, please give me feedback if it is useful and uncomfortable in practice, so as to know whether this set of rules is suitable for most people to use. According to everyone’s opinions, take the essence and discard the dregs to make this set of norms more practical.

Naming conventions

Project named

Use all lowercase letters and delimit by underscore. Example: my_project_name

The directory name

Refer to project naming rules;

When there is a complex number structure, use the plural nomenclature.

Examples: scripts, styles, images, data_models

Vue project, components under the component directory name, using the big hump command

Example: LeftBar

JS file naming

Refer to the project naming rules.

Example: account_model. Js

CSS, SCSS file name

Refer to the project naming rules.

Example: retina_sprites. CSS

HTML file naming

Refer to the project naming rules.

Example: error_log. HTML

HTML specification

Grammar:

  • Indent with TAB (2 Spaces);
  • Nested nodes should be indented;
  • On attributes, use double quotes, not single quotes;
  • Attribute names are all lowercase, delimited by hyphens (-).
  • Use a slash at the end of the auto-close label;

      
<html>
  <head>
    <title>Page title</title>
  </head>
  <body>
    <img src="images/company_logo.png" alt="Company" />

    <! Attribute names are all lowercase, delimited by a hyphen (-) -->
    <h1 class="hello-world">Hello, world!</h1>
  </body>
</html>
Copy the code

The standard model

Start standard mode by specifying a doctype at the beginning, which is capitalized.


      
<html>.</html>
Copy the code

Specified character encoding

Allows browsers to quickly and easily determine the appropriate rendering method for web content by declaring an explicit character encoding, usually specified as ‘UTF-8’.


      
<html>
  <head>
    <meta charset="UTF-8" />
  </head>.</html>
Copy the code

IE Compatible Mode

Use meta tags to specify which version of IE the page should be rendered with.


      
<html>
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
  </head>.</html>
Copy the code

Reduce the number of labels

When writing HTML code, you need to avoid redundant parent nodes;

<! -- bad -->
<span class="avatar">
  <img src="..." />
</span>

<! -- good -->
<img class="avatar" src="..." />
Copy the code

Semantic tag

HTML tags can use semantic tags, try to use semantic tags, avoid a page is all div or P tags

<! -- bad -->
<div>
  <p></p>
</div>

<! -- good -->
<header></header>
<footer></footer>
Copy the code

The CSS specification

The indentation

Use TAB indent (2 Spaces)

.element {
  border-radius: 10px;
  width: 50px;
  height: 50px;
}
Copy the code

A semicolon

End each declaration with a semicolon

.element {
  border-radius: 10px;
  width: 50px;
  height: 50px;
}
Copy the code

annotation

All comments use /* */

.element {
  /* border-radius: 10px; * /
  width: 50px;
  height: 50px;
}
Copy the code

quotes

  • Use quotation marks for the content of the URL
  • Attribute values in attribute selectors need quotes
.element:after { content: ""; background-image: url("logo.png"); } li[data-type="single"] { ... ; }Copy the code

named

  • Class names are lowercase letters separated by hyphens
  • The ID is named in camel shape
  • Variables, functions, mixers, placeholder in SCSS are named in camel shape
/* class */ .element-content { ... ; } /* id */ #myDialog { ... ; } /* variable */ $colorBlack: #000; / / @mixin centerBlock {... ; }Copy the code

JavaScript code

The indentation

Use TAB indent (2 Spaces)

if (x < y) {
  x += 10;
} else {
  x += 1;
}
Copy the code

Variable naming

  • Standard variables are named in camel shape
  • ‘Android’ capitalizes the first letter in the variable name
  • ‘iOS’ is the first letter in the variable name, followed by two uppercase letters
  • Constants are all uppercase and underlined
  • Constructor, uppercase the first letter
  • Jquery objects must be named starting with ‘$’
var thisIsMyName;

var AndroidVersion;

var iOSVersion;

var MAX_COUNT = 10;

function Person(name) {
  this.name = name;
}

// not good
var body = $("body");

// good
var $body = $("body");
Copy the code

Variable declarations

All variable declarations in a function scope refer to the function header as much as possible. Let and const are used if they can be used.

function doSomethingWithItems(items) {
  // use one var
  let value = 10,
    result = value + 10,
    i,
    len;

  for (i = 0, len = items.length; i < len; i++) {
    result += 10; }}Copy the code

The length of the line

Don’t exceed 100, but if the editor turns on Word Wrap, you can ignore the single line length.

A semicolon

A semicolon should be added.

The blank space

Do not write Spaces in the following cases:

  • Object after the property name
  • Function call before parentheses
  • Do not precede the ‘(‘ in function declarations or expressions
  • Array after ‘[‘ and before ‘]’
  • Operators ‘(‘ after and ‘)’ before

Be sure to write Spaces in the following cases:

  • The ternary operator ‘? Before and after: ‘
  • A comma must be followed by a space
  • Code block ‘{‘ before
  • Before: else, while, catch, finally
  • After the following keywords: if, else, for, while, do, switch, case, try,catch, finally, with, return, typeof
  • Single-line comments after ‘//’ (if single-line comments are the same as code, ‘//’ is also required), multi-line comments after ‘*’
  • Object before the property value
  • For loop, a semicolon followed by a space, and a comma followed by a space if there are more than one preconditions
  • In function declarations and expressions, always precede the ‘{‘ with a space
  • Between the parameters of a function

These are later formatted with esLint and prettier

Ex. :

// not good
var a = {
  b : 1
};

// good
var a = {
  b: 1
};

// not good
++x;
y++;
z = x ? 1:2;

// good
++x;
y++;
z = x ? 1 : 2;

// not good
var a = [ 1.2 ];

// good
var a = [1.2];

// good
var doSomething = function(a, b, c) {
  // do something
};

// good
doSomething(item);

// not good
for (let i = 0; i <6; i++) { x++; }// good
for (let i = 0; i < 6; i++) {
  x++;
}
Copy the code

A blank line

You must be free in the following situations

  • After a variable is declared (blank lines are not required when the variable is declared on the last line of the code block)
  • Before the comment (blank lines are not required when the comment is on the first line of the code block)
  • Leave a blank line at the end of the file
var x = 1;

// Comments should be preceded by empty lines
if (x >= 1) {
  var y = x + 1;
}
Copy the code

A newline

At the end of a line break there must be a ‘,’ or operator;

Line breaks are not required in the following cases:

  • Else, catch, finally
  • Code block ‘{‘ before

Line breaks are required in the following cases:

  • Code blocks ‘{‘ after and ‘}’ before
  • After the variable is assigned
// not good
var a = {
    b: 1
    , c: 2
};

x = y
    ? 1 : 2;

// good
var a = {
    b: 1.c: 2
};

x = y ? 1 : 2;

// good
if (condition) {
    ...
} else{... }try{... }catch (e) {
    ...
} finally{... }// not good
function test()
{... }// good
function test() {... }// not good
var a, foo = 7, b,
    c, bar = 8;

// good
var a,
    foo = 7,
    b, c, bar = 8;
Copy the code

annotation

Single-line comments

  • Comments on a single line should be followed by a space
  • Comments on the same line as the code are followed by a space after the semicolon and a space after the // comment

Ex. :

// Call the function
foo();

var maxCount = 10; // This is a variable
Copy the code

Multiline comment

Multi-line comments use the following form:

/** * 2 */
Copy the code

Multi-line comments are recommended in the following situations:

  • Difficult code snippets
  • There may be incorrect code snippets
  • Browser-specific HACK code
  • Code with strong business logic correlation

Function annotations

Complex functions, all classes, must be annotated, and function annotations use industry-wide specifications to facilitate subsequent documentation using JSDoc.

Ex. :

/** * get the task name * @param ID {Number} pass the character ID to get the name * @return {String} return the name * @author shi 2015/07/21 can not write * @version 1.1.0 */ * @example */
function getTaskName(id) {
  let name = "test";
  return name;
}
Copy the code

quotes

Single quotes are used for the outermost layer, except when strings are nested.

// not good
var x = "test";

// good
var y = 'foo',
  z = '<div id="test"></div>';
Copy the code

Objects, arrays

  • Object attribute names do not need to be quoted. For example, if object attribute names are underlined, they need to be quoted (rules of ESLint)

  • Objects are indented, not on a single line (a single property can be on a single line; es6 import methods can use a single line);

  • Arrays and objects should not end with commas.

// good
var a = {
  b: 1.c: 2
};
Copy the code

parentheses

Braces must follow the following keywords (even if the block is only one line) : if, else, for, while, do, switch, try, catch, finally, with.

// not good
if (condition) doSomething();

// good
if (condition) {
  doSomething();
}
Copy the code

undefined

Never use undefined directly for variable judgments;

Use typeof and the string ‘undefined’ to determine variables.

// not good
if (person === undefined) {... }// good
if (typeof person === 'undefined') {... }Copy the code

Multiple levels of nested conditional judgments and loops are not allowed (maximum three levels)

Do not use conditional judgments if you can use trigonometric and logical operators, but remember not to write too long trigonometric operators.

Ex. :

// bad
if (x === 10) {
  return 'valid';
} else {
  return 'invalid';
}

// good
return x === 10 ? 'valid' : 'invalid';

// bad
if(! x) {if(! y) { x =1;
  } else{ x = y; }}// good
x = x || y || 1;
Copy the code

Explain the logical operators, logical operators there are two main types, one is | | logic or, one is with && logic.

  • Logic or | | : the current one is true, before returning a value, before a false return a value.
var x = 1;
console.log(x || 2); / / 1

var y = 0;
console.log(y || 2); / / 2
Copy the code
  • Logic && : Returns the second value if the current one is true, and the previous value if the previous one is false.
var x = 1;
console.log(x && 2); / / 2

var y = 0;
console.log(y && 2); / / 0
Copy the code

Other ESlint

  • HasOwnProperty = hasOwnProperty;
  • Do not add methods to the prototype of built-in objects, such as Array, Date;
  • Do not use variables before declaring them;
  • Don’t just use constructors in a line of code; assign them to a variable;
  • Do not declare variables of the same name in the same scope;
  • Do not put parentheses in unnecessary places, for example: delete(a.b);
  • Do not use undeclared variables;
  • The debugger should not appear in submitted code;
  • Do not have empty elements in the array;
  • Do not declare functions inside loops;
  • Do not use constructors directly new (except new Vue());
  • Don’t declare variables and leave them unused;

These can be referred to eslint-config-alloy, which has detailed JS, TS, React and Vue specifications. We also introduced Tencent ESLint specifications when configuring ESLint later.

// good
for (key in obj) {
  if (obj.hasOwnProperty(key)) {
    // be sure that obj[key] belongs to the object and was not inherited
    console.log(obj[key]); }}// not good
Array.prototype.count = function(value) {
  return 4;
};

// not good
function test() {
  console.log(x);

  var x = 1;
}

// not good
new Person();

// good
var person = new Person();

// not good
delete (obj.attr);

// good
delete obj.attr;

// not good
var a = [1.2.3];

// not good
var nums = [];

// not good
for (var i = 0; i < 10; i++) {
  (function(i) {
    nums[i] = function(j) {
      return i + j;
    };
  })(i);
}
Copy the code

other

  • Use ‘LF’ for line breaks;
  • References to context this can only be named ‘_this’, ‘that’, or ‘self’;
  • No whitespace characters at the end of the line;
  • Empty blocks are not allowed (comments can be written in blocks if necessary).
// not good
function Person() {
  // not good
  var me = this;

  // good
  var _this = this;

  // good
  var that = this;

  // good
  var self = this;
}

if (condition) {
}
Copy the code

I have made a website for archiving this set of specifications with Vuepress, and you are welcome to check. www.shiyanping.top/code_rule, mainly attached to github page for deployment, also welcome everyone star my git project github.com/Shiyanping/… .

A link to the

  • Develop your own front-end development specification for ESLint

  • Hand touch brings you to practice standard front-end development specifications

Read the last two songs

Thank you very much for taking the time to finish reading. I sincerely hope that you can spend a little time to help with two things:

  • Move your finger and give me a “like”. Your “like” is the biggest motivation for me.

  • I hope you pay attention to my public account, the first time the new article to the public account, the public account mainly sent some personal essays, reading notes, and some technical hot spots and real-time hot spots, and there is a very attractive my own money lottery oh ~