Front-end development specification

A, HTML

1. Semantic labels

HTML5 provides a lot of semantic elements to help better describe content. Hopefully you will benefit from these rich tag libraries.


<! -- bad --> <div id="main"> <div class="article"> <div class="header"> <h1>Blog post</h1> <p>Published: <span>21st Feb, 2015</span></p> </div> <p>... </p> </div> </div> <! -- good --> <main> <article> <header> <h1>Blog post</h1> <p>Published: <time dateTime ="2015-02-21">21st Feb, 2015</time></p> </header> <p>... </p> </article> </main>Copy the code


 

Be sure to use semantically correct tags; the wrong ones are worse than the conservative ones.


<! -- bad --> <h1> <figure> <img alt=Company src=logo.png> </figure> </h1> <! -- good --> <h1> <img alt=Company src=logo.png> </h1>Copy the code


concise

Keep your code simple and don’t go back to XHTML’s old ways.


<! -- bad --> <! doctype html> <html lang=en> <head> <meta http-equiv=Content-Type content="text/html; charset=utf-8" /> <title>Contact</title> <link rel=stylesheet href=style.css type=text/css /> </head> <body> <h1>Contact  me</h1> <label> Email address: <input type=email [email protected] required=required /> </label> <script src=main.js type=text/javascript></script> </body> </html> <! -- good --> <! doctype html> <html lang=en> <meta charset=utf-8> <title>Contact</title> <link rel=stylesheet href=style.css> <h1>Contact me</h1> <label> Email address: <input type=email [email protected] required> </label> <script src=main.js></script> </html>Copy the code


HTML5 doctype

Adding a standard Mode declaration for the first line of each HTML page ensures a consistent rendering across browsers.


<! DOCTYPE html> <html> <head> </head> </html>Copy the code


Language attributes

According to the HTML5 specification:


It is strongly recommended to specify the lang attribute for the HTML root element to set the correct language for the document. This will help speech synthesis tools determine the pronunciation they should use, translation tools determine the rules they should follow when translating, and so on.Copy the code


You can learn more about lang attributes from this specification.

Here is a list of language codes.


<html lang="en"> <! -... --> </html>Copy the code


IE Compatible Mode

IE supports specific <meta> tags to determine which version of IE should be used to draw the current page. Unless there is a strong special need, it is best to set edge mode to inform IE to adopt the latest mode it supports.

Read this article on Stack Overflow for more useful information.


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


A character encoding

By explicitly declaring character encodings, you ensure that browsers can quickly and easily determine how page content should be rendered. This has the advantage of avoiding the use of character entity tags in THE HTML and thus being entirely consistent with the document encoding (typically UTF-8).


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


availability

Usability should not be an afterthought. You can do great things with simple changes such as:

  • Use Alt attributes correctly
  • Make sure links and buttons are used correctly (don’t use them)<div class=button>This crude approach)
  • Does not rely on color to convey information
  • Label the form with lable tags


<! -- bad --> <h1><img alt="Logo" src="logo.png"></h1> <! -- good --> <h1><img alt="My Company, Inc." src="logo.png"></h1>Copy the code


performance

Do not load the script before loading the content unless it is absolutely necessary to do so, as this will impede web rendering. If your stylesheets are large, they must be kept in a separate file. Two HTTP requests do not significantly degrade performance.


<! -- bad --> <! doctype html> <meta charset=utf-8> <script src=analytics.js></script> <title>Hello, world.</title> <p>... </p> <! -- good --> <! doctype html> <meta charset=utf-8> <title>Hello, world.</title> <p>... </p> <script src=analytics.js></script>Copy the code


Attribute order

HTML attributes should appear in a specific order to ensure readability.


id class name data-xxx src, for, type, href title, alt aria-xxx, role value styleCopy the code


Second, the CSS

A semicolon

Do not omit a semicolon


/* bad */
div {
  color: red
}

/* good */
div {
  color: red;
}Copy the code


flow

Try not to change the element default behavior. Keep the default text flow. For example, removing a white block from an image does not affect the original display:


/* bad */
img {
  display: block;
}

/* good */
img {
  vertical-align: middle;
}Copy the code


Similarly, try not to change the float.


/* bad */
div {
  width: 100px;
  position: absolute;
  right: 0;
}

/* good */
div {
  width: 100px;
  margin-left: auto;
}Copy the code


The selector

Tightly coupled DOM selectors, three levels above the recommended class:


/* bad */
div:first-of-type :last-child > p ~ *

/* good */
div:first-of-type .infoCopy the code


Avoid unnecessary writing:


/* bad */
img[src$=svg], ul > li:first-child {
  opacity: 0;
}

/* good */
[src$=svg], ul > :first-child {
  opacity: 0;
}Copy the code


Indicate the

Don’t make your code hard to rewrite, make your selectors more precise, reduce ids, and avoid them! important


/* bad */ .bar { color: green ! important; } .foo { color: red; } /* good */ .foo.bar { color: green; } .foo { color: red; }Copy the code


cover

Overwriting styles can make maintenance and debugging more difficult, so avoid them.


/* bad */
li {
  visibility: hidden;
}
li:first-child {
  visibility: visible;
}

/* good */
li + li {
  visibility: hidden;
}Copy the code


inheritance

Do not declare inheritable styles repeatedly:


/* bad */
div h1, div p {
  text-shadow: 0 1px 0 #fff;
}

/* good */
div {
  text-shadow: 0 1px 0 #fff;
}Copy the code


simplicity

Keep your code simple. Use attribute abbreviations. Don’t write unnecessary values.


/* bad */
div {
  transition: all 1s;
  top: 50%;
  margin-top: -10px;
  padding-top: 5px;
  padding-right: 10px;
  padding-bottom: 20px;
  padding-left: 10px;
}

/* good */
div {
  transition: 1s;
  top: calc(50% - 10px);
  padding: 5px 10px 20px;
}Copy the code


language

Don’t use numbers when you can use English.


/* bad */
:nth-child(2n + 1) {
  transform: rotate(360deg);
}

/* good */
:nth-child(odd) {
  transform: rotate(1turn);
}Copy the code


animation

Use Transition as much as possible, except for animation to transform and change transparency.


/* bad */
div:hover {
  animation: move 1s forwards;
}
@keyframes move {
  100% {
    margin-left: 100px;
  }
}

/* good */
div:hover {
  transition: 1s;
  transform: translateX(100px);
}Copy the code


unit

Don’t use units when you can. Rem is recommended. Time in s is better than in ms.


/* bad */ div { margin: 0px; font-size: .9em; line-height: 22px; transition: 500ms; } /* good */ div { margin: 0; font-size: .9rem; The line - height: 1.5; transition: .5s; }Copy the code


color

To make transparent effects, use RGBA, otherwise use hexadecimal:


/* bad */
div {
  color: hsl(103, 54%, 43%);
}

/* good */
div {
  color: #5a3;
}Copy the code


drawing

Reduce HTTPS requests and replace images with CSS drawings as much as possible:


/* bad */
div::before {
  content: url(white-circle.svg);
}

/* good */
div::before {
  content: "";
  display: block;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background: #fff;
}Copy the code


annotation


/* bad */
div {
  // position: relative;
  transform: translateZ(0);
}

/* good */
div {
  /* position: relative; */
  will-change: transform;
}Copy the code


grammar

  • Replace tabs with two Spaces — this is the only way to guarantee consistent presentation across all environments.
  • When grouping selectors, place individual selectors on a single line.
  • For legibility of code, add a space before the opening curly brace of each declaration block.
  • The closing curly brace of the declaration block should be a separate line.
  • A space should be inserted after the: of each declaration statement.
  • For more accurate error reporting, each statement should have a single line.
  • All declarations should end with a semicolon. The semicolon following the last declaration is optional, but if you omit it, your code may be more prone to errors.
  • For comma-separated attribute values, a space should be inserted after each comma (for example, box-shadow).
  • Do not insert Spaces after commas inside RGB (), RGBA (), HSL (), HSLA (), or RECt () values. This makes it easier to distinguish multiple color values (comma only, no space) from multiple attribute values (both comma and space).


/* Bad CSS */ .selector, .selector-secondary, .selector[type=text] { padding:15px; margin:0px 0px 15px; Background - color: rgba (0, 0, 0, 0.5); box-shadow:0px 1px 2px #CCC,inset 0 1px 0 #FFFFFF } /* Good CSS */ .selector, .selector-secondary, .selector[type="text"] { padding: 15px; margin-bottom: 15px; Background - color: rgba (0, 0, 5); box-shadow: 0 1px 2px #ccc, inset 0 1px 0 #fff; }Copy the code


Id and class name

* Class should be named after functional content, not representation, a generic and meaningful word

* The class and ID words are lowercase letters. If there are multiple words, separate them with hyphens (-)

Activate and hover effects class

Use on as the class for the active state and hover as the class for the moved element

The order in which styles are declared

1, positioning

2. Box model

3. On words

4. About color and background

4, cursor:pointer


. Declaration -order {/* position: absolute; top: 0; right: 0; bottom: 0; left: 0; z-index: 100; /* box model */ display: block; box-sizing: border-box; width: 100px; height: 100px; padding: 10px; border: 1px solid #e5e5e5; border-radius: 3px; margin: 10px; float: right; overflow: hidden; Font: normal 13px "Helvetica Neue", sans-serif; The line - height: 1.5; text-align: center; /* color: #f5f5f5; /* color: #f5f5f5; color: #fff; opacity: .8; /* other */ cursor: pointer; }Copy the code


Less syntax specification

1. Variable, mixed use

Variables, mixing, allow us to define a set of generic styles individually and then call them as needed. So some common style rules can be defined in a separate less file, called elsewhere, and easily modified when making global style adjustments


// LESS @color: #4D926F; #header { color: @color; } h2 { color: @color; } /* Generated CSS */ #header {color: #4D926F; } h2 { color: #4D926F; } //LESS .bordered { border-top: dotted 1px black; border-bottom: solid 2px black; } #menu a { color: #111; .bordered; } .post a { color: red; .bordered; } /* Generated CSS */ #menu a {color: #111; border-top: dotted 1px black; border-bottom: solid 2px black; } .post a { color: red; border-top: dotted 1px black; border-bottom: solid 2px black; }Copy the code


2. Nesting rules (avoid too many nesting levels)

Limit the nesting depth to 2-3 levels. For nesting beyond 3 levels, re-evaluation is given. This avoids overly verbose CSS selectors. Avoid lots of nested rules. Interrupt when readability is affected. It is recommended to avoid nesting rules with more than 20 lines.


#header {
  color: black;

  .navigation {
    font-size: 12px;
  }
  .logo {
    width: 300px;
    &:hover { text-decoration: none }
  }
}
Copy the code


3. Namespace

Sometimes, you might want to bundle variables or mixed modules together for better CSS organization or simply for better encapsulation. You can define a set of properties in the #bundle that you can reuse:


#bundle { .button () { display: block; border: 1px solid black; background-color: grey; &:hover { background-color: white } } .tab { ... } .citation { ... #header a {color: orange;}} #header a {color: orange; #bundle > .button; }Copy the code


Most of the above HTML and CSS specifications refer to github frontend-guidelines and coding specifications by@mdo (the following ones are added by myself

Three, JavaScript,

The javascript specification uses the Standard, the benefits of which can be seen in the hyperlink. NPM, Github, and others use this Standard. The following copy Standard Style rules are used with ESLint

1. Indent with two Spaces.

eslint: indent


function hello (name) {
  console.log('hi', name)
}Copy the code





2. Use single quotation marks (" quotes ") for strings except for escaped cases. eslint: quotes console.log('hello there') $("<div class='box'>") 3. Do not define unused variables. eslint: no-unused-vars function myFunction () { var result = something() // avoid } 4. Add Spaces after the keyword. eslint: keyword-spacing if (condition) { ... } // ok if(condition) { ... } // avoid 5. Add Spaces between parentheses and function names when declaring functions. eslint: space-before-function-paren function name (arg) { ... } // ok function name(arg) { ... } // avoid run(function () { ... }) // ok run(function() { ... }) // avoid 6. Always use === instead of == Exception: obj = = null can be used to check the null | | is undefined. eslint: eqeqeq if (name === 'John') // ok if (name == 'John') // avoid if (name ! == 'John') // ok if (name ! = 'John') // avoid 7. Leave Spaces between Infix operators. eslint: space-infix-ops // ok var x = 2 var message = 'hello, ' + name + '! ' // avoid var x=2 var message = 'hello, '+name+'! '8. Space after commas. eslint: comma-spacing // ok var list = [1, 2, 3, 4] function greet (name, options) { ... } // avoid var list = [1,2,3,4] function greet (name,options) {// avoid var list = [1,2,3,4] function greet (name,options) { } 9. The else keyword should be kept on the same line as the curly braces. eslint: brace-style // ok if (condition) { // ... } else { // ... } // avoid if (condition) { // ... } else { // ... } 10. Multiline if statements cannot omit parentheses. eslint: curly // ok if (options.quiet ! == true) console.log('done') // ok if (options.quiet ! == true) { console.log('done') } // avoid if (options.quiet ! == true) console.log('done') 11. Do not discard the ERR parameter in exception handling. eslint: handle-callback-err // ok run(function (err) { if (err) throw err window.alert('done') }) // avoid run(function (err) { window.alert('done') }) 12. Use browser global variables with the window. Prefix. Exception: Document, console and Navigator ESLint: no-undef window.alert('hi') // ok 13. Consecutive multiple blank lines are not allowed. eslint: no-multiple-empty-lines // ok var value = 'hello world' console.log(value) // avoid var value = 'hello world' console.log(value) 14. For ternary operators? And: on the same line as the code they are responsible for. eslint: operator-linebreak // ok var location = env.development ? 'localhost' : 'www.api.com' // ok var location = env.development ? 'localhost' : 'www.api.com' // avoid var location = env.development ? 'localhost' : 'www.api.com' 15. Each var keyword declares a separate variable. eslint: one-var // ok var silent = true var verbose = true // avoid var silent = true, verbose = true // avoid var silent = true, verbose = true 16. Conditional statements are surrounded by parentheses. This makes the code more legible and readable than if the full equal sign (===) of the conditional statement had been incorrectly written as an equal sign (=). eslint: no-cond-assign // ok while ((m = text.match(expr))) { // ... } // avoid while (m = text.match(expr)) { // ... } 17. Single line code block with Spaces. eslint: block-spacing function foo () {return true} // avoid function foo () { return true } // ok 18. Use hump nomenclature for variable and function names. eslint: camelcase function my_function () { } // avoid function myFunction () { } // ok var my_var = 'hello' // avoid var myVar = 'hello' // ok 19. No extra end-of-line commas are allowed. eslint: comma-dangle var obj = { message: 'hello', // avoid } 20. Always place the comma at the end of the line. eslint: comma-style var obj = { foo: 'foo' ,bar: 'bar' // avoid } var obj = { foo: 'foo', bar: 'bar' // ok }Copy the code





21.文件末尾留一空行。
elint: eol-last
22.函数调用时标识符与括号间不留间隔。
eslint: func-call-spacing
console.log ('hello') //  avoid
console.log('hello')  //  ok
23.键值对当中冒号与值之间要留空白。
eslint: key-spacing
var obj = { 'key' : 'value' }    //  avoid
var obj = { 'key' :'value' }     //  avoid
var obj = { 'key':'value' }      //  avoid
var obj = { 'key': 'value' }     //  ok
24.构造函数要以大写字母开头。
eslint: new-cap
function animal () {}
var dog = new animal()    //  avoid
function Animal () {}
var dog = new Animal()    //  ok
25.无参的构造函数调用时要带上括号。
eslint: new-parens
function Animal () {}
var dog = new Animal    //  avoid
var dog = new Animal()  //  ok
26.对象中定义了存值器,一定要对应的定义取值器。
eslint: accessor-pairs
var person = {
  set name (value) {    //  avoid
    this.name = value
  }
}
var person = {
  set name (value) {
    this.name = value
  },
  get name () {         //  ok
    return this.name
  }
}
27.子类的构造器中一定要调用 super
eslint: constructor-super
class Dog {
  constructor () {
    super()   //  avoid
  }
}

class Dog extends Mammal {
  constructor () {
    super()   //  ok
  }
}
28.使用数组字面量而不是构造器。
eslint: no-array-constructor
var nums = new Array(1, 2, 3)   //  avoid
var nums = [1, 2, 3]            //  ok
29.避免使用 arguments.callee 和 arguments.caller。
eslint: no-caller
function foo (n) {
  if (n <= 0) return

  arguments.callee(n - 1)   //  avoid
}

function foo (n) {
  if (n <= 0) return

  foo(n - 1)
}
30.避免对类名重新赋值。
eslint: no-class-assign
class Dog {}
Dog = 'Fido'    //  avoid
31.避免修改使用 const 声明的变量。
eslint: no-const-assign
const score = 100
score = 125       //  avoid
32.避免使用常量作为条件表达式的条件(循环语句除外)。
eslint: no-constant-condition
if (false) {    //  avoid
  // ...
}

if (x === 0) {  //  ok
  // ...
}

while (true) {  //  ok
  // ...
}
33.正则中不要使用控制符。
eslint: no-control-regex
var pattern = /\x1f/    //  avoid
var pattern = /\x20/    //  ok
34.不要使用 debugger。
eslint: no-debugger
function sum (a, b) {
  debugger      //  avoid
  return a + b
}
35.不要对变量使用 delete 操作。
eslint: no-delete-var
var name
delete name     //  avoid
36.不要定义冗余的函数参数。
eslint: no-dupe-args
function sum (a, b, a) {  //  avoid
  // ...
}

function sum (a, b, c) {  //  ok
  // ...
}
37.类中不要定义冗余的属性。
eslint: no-dupe-class-members
class Dog {
  bark () {}
  bark () {}    //  avoid
}
38.对象字面量中不要定义重复的属性。
eslint: no-dupe-keys
var user = {
  name: 'Jane Doe',
  name: 'John Doe'    //  avoid
}
39.switch 语句中不要定义重复的 case 分支。
eslint: no-duplicate-case
switch (id) {
  case 1:
    // ...
  case 1:     //  avoid
}
40.同一模块有多个导入时一次性写完。
eslint: no-duplicate-imports
import { myFunc1 } from 'module'
import { myFunc2 } from 'module'          //  avoid

import { myFunc1, myFunc2 } from 'module' //  ok
41.正则中不要使用空字符。
eslint: no-empty-character-class
const myRegex = /^abc[]/      //  avoid
const myRegex = /^abc[a-z]/   //  ok
42.不要解构空值。
eslint: no-empty-pattern
const { a: {} } = foo         //  avoid
const { a: { b } } = foo      //  ok
43.不要使用 eval()。
eslint: no-eval
eval( "var result = user." + propName ) //  avoid
var result = user[propName]             //  ok
44.catch 中不要对错误重新赋值。
eslint: no-ex-assign
try {
  // ...
} catch (e) {
  e = 'new value'             //  avoid
}

try {
  // ...
} catch (e) {
  const newVal = 'new value'  //  ok
}
45.不要扩展原生对象。
eslint: no-extend-native
Object.prototype.age = 21     //  avoid
46.避免多余的函数上下文绑定。
eslint: no-extra-bind
const name = function () {
  getName()
}.bind(user)    //  avoid

const name = function () {
  this.getName()
}.bind(user)    //  ok
47.避免不必要的布尔转换。
eslint: no-extra-boolean-cast
const result = true
if (!!result) {   //  avoid
  // ...
}

const result = true
if (result) {     //  ok
  // ...
}
48.不要使用多余的括号包裹函数。
eslint: no-extra-parens
const myFunc = (function () { })   //  avoid
const myFunc = function () { }     //  ok
49.switch 一定要使用 break 来将条件分支正常中断。
eslint: no-fallthrough
switch (filter) {
  case 1:
    doSomething()    //  avoid
  case 2:
    doSomethingElse()
}

switch (filter) {
  case 1:
    doSomething()
    break           //  ok
  case 2:
    doSomethingElse()
}

switch (filter) {
  case 1:
    doSomething()
    // fallthrough //  ok
  case 2:
    doSomethingElse()
}
50.不要省去小数点前面的0。
eslint: no-floating-decimal
const discount = .5      //  avoid
const discount = 0.5     //  ok
51.避免对声明过的函数重新赋值。
eslint: no-func-assign
function myFunc () { }
myFunc = myOtherFunc    //  avoid
52.不要对全局只读对象重新赋值。
eslint: no-global-assign
window = {}     //  avoid
53.注意隐式的 eval()。
eslint: no-implied-eval
setTimeout("alert('Hello world')")                   //  avoid
setTimeout(function () { alert('Hello world') })     //  ok
54.嵌套的代码块中禁止再定义函数。
eslint: no-inner-declarations
if (authenticated) {
  function setAuthUser () {}    //  avoid
}
55.不要向 RegExp 构造器传入非法的正则表达式。
eslint: no-invalid-regexp
RegExp('[a-z')    //  avoid
RegExp('[a-z]')   //  ok
56.不要使用非法的空白符。
eslint: no-irregular-whitespace
function myFunc () /*<NBSP>*/{}   //  avoid
57.禁止使用 iterator。
eslint: no-iterator
Foo.prototype.__iterator__ = function () {}   //  avoid
58.外部变量不要与对象属性重名。
eslint: no-label-var
var score = 100
function game () {
  score: 50         //  avoid
}
59.不要使用标签语句
eslint: no-labels
label:
  while (true) {
    break label     //  avoid
  }
60.不要书写不必要的嵌套代码块。
eslint: no-lone-blocks
function myFunc () {
  {                   //  avoid
    myOtherFunc()
  }
}

function myFunc () {
  myOtherFunc()       //  ok
}
61.不要混合使用空格与制表符作为缩进。
eslint: no-mixed-spaces-and-tabs
62.除了缩进,不要使用多个空格。
eslint: no-multi-spaces
const id =    1234    //  avoid
const id = 1234       //  ok
63.不要使用多行字符串。
eslint: no-multi-str
const message = 'Hello \ world'     //  avoid
64.new 创建对象实例后需要赋值给变量。
eslint: no-new
new Character()                     //  avoid
const character = new Character()   //  ok
65.禁止使用 Function 构造器。
eslint: no-new-func
var sum = new Function('a', 'b', 'return a + b')    //  avoid
66.禁止使用 Object 构造器。
eslint: no-new-object
let config = new Object()   //  avoid
67.禁止使用 new require。
eslint: no-new-require
const myModule = new require('my-module')    //  avoid
68.禁止使用 Symbol 构造器。
eslint: no-new-symbol
const foo = new Symbol('foo')   //  avoid
69.禁止使用原始包装器。
eslint: no-new-wrappers
const message = new String('hello')   //  avoid
70.不要将全局对象的属性作为函数调用。
eslint: no-obj-calls
const math = Math()   //  avoid
71.不要使用八进制字面量。
eslint: no-octal
const num = 042     //  avoid
const num = '042'   //  ok
72.字符串字面量中也不要使用八进制转义字符。
eslint: no-octal-escape
const copyright = 'Copyright \251'  //  avoid
73.使用 __dirname 和 __filename 时尽量避免使用字符串拼接。
eslint: no-path-concat
const pathToFile = __dirname + '/app.js'            //  avoid
const pathToFile = path.join(__dirname, 'app.js')   //  ok
74.使用 getPrototypeOf 来替代 proto。
eslint: no-proto
const foo = obj.__proto__               //  avoid
const foo = Object.getPrototypeOf(obj)  //  ok
75.不要重复声明变量。
eslint: no-redeclare
let name = 'John'
let name = 'Jane'     //  avoid

let name = 'John'
name = 'Jane'         //  ok
76.正则中避免使用多个空格。
eslint: no-regex-spaces
const regexp = /test value/   //  avoid

const regexp = /test {3}value/  //  ok
const regexp = /test value/     //  ok
77.return 语句中的赋值必需有括号包裹。
eslint: no-return-assign
function sum (a, b) {
  return result = a + b     //  avoid
}

function sum (a, b) {
  return (result = a + b)   //  ok
}
78.避免将变量赋值给自己。
eslint: no-self-assign
name = name   //  avoid
79.避免将变量与自己进行比较操作。
esint: no-self-compare
if (score === score) {}   //  avoid
80.避免使用逗号操作符。
eslint: no-sequences
if (doSomething(), !!test) {}   //  avoid
81.不要随意更改关键字的值。
eslint: no-shadow-restricted-names
let undefined = 'value'     //  avoid
82.禁止使用稀疏数组(Sparse arrays)。
eslint: no-sparse-arrays
let fruits = ['apple',, 'orange']       //  avoid
83.不要使用制表符。
eslint: no-tabs
84.正确使用 ES6 中的字符串模板。
eslint: no-template-curly-in-string
const message = 'Hello ${name}'   //  avoid
const message = `Hello ${name}`   //  ok
85.使用 this 前请确保 super() 已调用。
eslint: no-this-before-super
class Dog extends Animal {
  constructor () {
    this.legs = 4     //  avoid
    super()
  }
}
86.用 throw 抛错时,抛出 Error 对象而不是字符串。
eslint: no-throw-literal
throw 'error'               //  avoid
throw new Error('error')    //  ok
87.行末不留空格。
eslint: no-trailing-spaces
88.不要使用 undefined 来初始化变量。
eslint: no-undef-init
let name = undefined    //  avoid

let name
name = 'value'          //  ok
Copy the code





Update loop variables in loop statements. eslint: no-unmodified-loop-condition for (let i = 0; i < items.length; j++) {... } // avoid for (let i = 0; i < items.length; i++) {... } // ok 90. If there is a better implementation, try not to use ternary expressions. eslint: no-unneeded-ternary let score = val ? Val: 0 / / get the let score = val | | 0 / / ok 91. Return, throw, don't again after the continue and break with the code. eslint: No-unreachable function doSomething () {return true console.log('never called') // avoid} 92.finally eslint: no-unsafe-finally try { // ... } catch (e) { // ... } finally { return 42 // avoid } 93. Do not invert the lvalue of a relational operator. eslint: no-unsafe-negation if (! Key in obj) {} // avoid unnecessary.call() and.apply(). eslint: no-useless-call sum.call(null, 1, 2, 3) // avoid 95. Avoid using unnecessary computed values for object attributes. eslint: no-useless-computed-key const user = { ['name']: 'John Doe' } // avoid const user = { name: 'John Doe' } // ok 96. Disallow redundant constructors. eslint: no-useless-constructor class Car { constructor () { // avoid } } 97. Prohibit unnecessary escapes. Eslint: no-useless-escape let message = 'Hell\o' // avoid 98.import, export and destruct operations disallow assignment to a variable of the same name. eslint: no-useless-rename import { config as config } from './config' // avoid import { config } from './config' // ok 99. Properties are not preceded by Spaces. eslint: no-whitespace-before-property user .name // avoid user.name // ok 100. Do not use with. eslint: no-with with (val) {... } // avoid 101. eslint: object-property-newline const user = { name: 'Jane Doe', age: 30, username: 'jdoe86' // avoid } const user = { name: 'Jane Doe', age: 30, username: 'jdoe86' } // ok const user = { name: 'Jane Doe', age: 30, username: 'jdoe86' } 102. Avoid extra white space in code blocks. eslint: padded-blocks if (user) { // avoid const name = getName() } if (user) { const name = getName() // ok } 103. Do not leave a space between the expansion operator and its expression. eslint: rest-spread-spacing fn(... args) // avoid fn(... Args) // ok 104. If semicolons are encountered, Spaces should be left after and before. eslint: semi-spacing for (let i = 0 ; i < items.length ; i++) {... } // avoid for (let i = 0; i < items.length; i++) {... } // ok 105. eslint: space-before-blocks if (admin){... } // avoid if (admin) {... } // ok 107. Leave no Spaces between parentheses ESlint: space-in-parens getName(name) // Avoid getName(name) // ok 107. The unary operator is followed by a space. eslint: space-unary-ops typeof! admin // avoid typeof ! Admin // OK 108. Leave Spaces at the beginning and end of comments. eslint: spaced-comment //comment // avoid // comment // ok /*comment*/ // avoid /* comment */ // ok 109. There are no Spaces before or after variables in the template string. eslint: template-curly-spacing const message = `Hello, ${ name }` // avoid const message = `Hello, ${name}` // ok 110. The correct posture for checking NaN is to use isNaN(). eslint: use-isnan if (price === NaN) { } // avoid if (isNaN(price)) { } // ok 111. Use a valid string to compare operations with typeof. eslint: valid-typeof typeof name === 'undefimed' // avoid typeof name === 'undefined' // ok 112. Self-calling anonymous functions (IIFEs) are wrapped in parentheses. eslint: wrap-iife const getName = function () { }() // avoid const getName = (function () { }()) // ok const getName = (function () {})() // ok 113. Yield * must be preceded by Spaces. eslint: yield-star-spacing yield* increment() // avoid yield * increment() // ok 114. Avoid Yoda conditions. eslint: yoda if (42 === age) { } // avoid if (age === 42) { } // ok 115. Use a semicolon. eslint: semi window.alert('hi') // avoid window.alert('hi'); Do not start a line with (, [, or ', etc.). Compression without a semicolon will result in an error, and sticking to this specification will avoid errors. no-unexpected-multiline ** // ok ; (function () { window.alert('ok') }()) // avoid (function () { window.alert('ok') }()) // ok ; [1, 2, 3]. The forEach (bar) / / get [1, 2, 3] forEach (bar) / / ok; ` hello. ` indexOf (' o ') / / get ` hello. ` indexOf (' o ') note: ;[1, 2, 3]. ForEach (bar) suggests var nums = [1, 2, 3].Copy the code


Es6 syntax specification

1. Let replace var

ES6 introduced two new commands to declare variables: let and const. Among them, let can completely replace VAR because the semantics are the same and let has no side effects.

2. Global const

In a global environment, variables should not be set, only constants should be set

Benefits: Const is superior to LET for several reasons. One is const to remind the reader that this variable should not change; The other is that const is more functional. Operations don’t change values, they just create new values, and this is also good for future distributed operations. The final reason is that JavaScript compilers optimize for const, so using const makes your program more efficient. In other words, the essential difference between lets and const is the internal processing of the compiler. A const declaration of a constant has two additional benefits. One is that readers of the code immediately realize that the value should not be changed, and the other is that it prevents errors caused by unintentional changes to the value of a variable.


3. Use destruct assignment. When assigning to a variable using an array member, destruct assignment is preferred. const arr = [1, 2, 3, 4]; // bad const first = arr[0]; const second = arr[1]; // good const [first, second] = arr; Function arguments that are members of an object use destruct assignment preferentially. // bad function getFullName(user) { const firstName = user.firstName; const lastName = user.lastName; } // good function getFullName(obj) { const { firstName, lastName } = obj; } // best function getFullName({firstName, lastName}) {} If the function returns multiple values, the destruct assignment of the object is preferred over the destruct assignment of the array. This makes it easy to add the return values later and change the order in which they are returned. // bad function processInput(input) { return [left, right, top, bottom]; } // good function processInput(input) { return { left, right, top, bottom }; } const { left, right } = processInput(input); 4. Objects Objects should be static as much as possible. Once defined, new attributes should not be added arbitrarily. If adding attributes is unavoidable, use the object. assign method. // bad const a = {}; a.x = 3; // if reshape unavoidable const a = {}; Object.assign(a, { x: 3 }); // good const a = { x: null }; a.x = 3; If an object's attribute name is dynamic, you can define it using an attribute expression when creating the object. // bad const obj = { id: 5, name: 'San Francisco', }; obj[getKey('enabled')] = true; // good const obj = { id: 5, name: 'San Francisco', [getKey('enabled')]: true, }; In addition, object attributes and methods, as far as possible concise expression method, so easy to describe and write. var ref = 'some value'; // bad const atom = { ref: ref, value: 1, addValue: function (value) { return atom.value + value; }}; // good const atom = { ref, value: 1, addValue(value) { return atom.value + value; }}; 5. Arrays use extension operators (...) Copy the array. // bad const len = items.length; const itemsCopy = []; let i; for (i = 0; i < len; i++) { itemsCopy[i] = items[i]; } // good const itemsCopy = [...items]; Convert an array-like object into an Array using the array. from method. const foo = document.querySelectorAll('.foo'); const nodes = Array.from(foo); Functions execute immediately functions can be written in the form of arrow functions. (() => { console.log('Welcome to the Internet.'); }) (); Where functional expressions are required, use arrow functions instead. Because it's cleaner, and it's bound to this. // bad [1, 2, 3].map(function (x) { return x * x; }); // good [1, 2, 3].map((x) => { return x * x; }); // best [1, 2, 3].map(x => x * x); Simple, single-line, non-reusable functions, the arrow function is recommended. If the body of the function is complex and the number of lines is large, the traditional function writing method should be used. 7.Map Structure Pay attention to the distinction between Object and Map. Object is used only when simulating real world entity objects. If you only need a key: value data structure, use the Map structure. Because Map has a built-in traversal mechanism. let map = new Map(arr); for (let key of map.keys()) { console.log(key); } for (let value of map.values()) { console.log(value); } for (let item of map.entries()) { console.log(item[0], item[1]); } 8. Class always uses class instead of prototype operations. Because Class is more concise and easier to understand. // bad function Queue(contents = []) { this._queue = [...contents]; } Queue.prototype.pop = function() { const value = this._queue[0]; this._queue.splice(0, 1); return value; } // good class Queue { constructor(contents = []) { this._queue = [...contents]; } pop() { const value = this._queue[0]; this._queue.splice(0, 1); return value; }} use extends for inheritance because it's simpler and doesn't risk breaking the instanceof operation. // bad const inherits = require('inherits'); function PeekableQueue(contents) { Queue.apply(this, contents); } inherits(PeekableQueue, Queue); PeekableQueue.prototype.peek = function() { return this._queue[0]; } // good class PeekableQueue extends Queue { peek() { return this._queue[0]; }} 9. As a general rule, do not define a failed state callback in the then method (i.e. the second argument to the THEN). Then (function(data) {// success}, function(err) {// error}); // good promise .then(function(data) { //cb // success }) .catch(function(err) { // error });Copy the code


new

i++

Don’t use I ++, use I +=1; (Except for for loop)

Iv. Vue specification

1. Placement sequence of VUE method

1.1 the components

1.2 props

1.3 the data

1.4 created

1.5 mounted

1.6 activited

The 1.7 update

1.8 beforeRouteUpdate

1.9 metods

1.10 the filter

1.11 the computed

1.12 watch

2. Method Name a custom method

2.1 Object phrases (good: jumpPage, openCarInfoDialog) (bad: go, nextPage, show, open, login)

2.2 Ajax methods start with get and POST and end with Data (good: getListData, postFormData) (bad: takeData, confirmData, getList, postForm)

2.3 Event methods start with ON (onTypeChange, onUsernameInput)

2.4 Except for the words init and refresh

2.5 Start with common words (set, get, open, close, jump)

2.6 Camel Name (good: getListData) (BAD: get_list_data, getListData)

3. Life cycle approach points to note

SQL > create; SQL > create; SQL > create

3.2 Listening for Bus events in CREATED

4. Module based development

Principle: Each VUE component must first focus on solving a single problem, independent, reusable, small and testable. If your component does too much or becomes bloated, break it down into smaller components and keep to a single principle.









5.Vue component naming meaningful: not too specific, not too abstract Short: 2 to 3 words readable: to facilitate communication <! Recommend -- - > < app - the header > < / app - the header > < user - the list > < / user - the list > < range - the slider > < / range - the slider > <! -- Avoid --> <btn-group></btn-group> <! Short but not very readable. Use 'button-group' instead -> < uI-slider ></ UI-slider ><! --> <slider></slider> <! -- incompatible with custom element specifications --> 6. Validate component props provides default values. Verify the type using the type attribute. Check that the prop exists before using props. <template> <input type="range" v-model="value" :max="max" :min="min"> </template> <script type="text/javascript"> export Default {props: {Max: {type: Number, // }, }, min: { type: Number, default() { return 0; }, }, value: { type: Number, default() { return 4; }},}}; </script>Copy the code


7. Create components only when needed

Vue.js is a component-based framework. If you do not know when to create a component you may have the following problems:

  • If the component is too large, it may be difficult to reuse and maintain;
  • If components are too small, your project will drown (because of deep nesting) and it will be harder for components to communicate;

The rules

  • First, try to build obvious (generic) components like modal boxes, prompt boxes, toolbars, menus, headers, and so on as early as possible. In short, you know that these components will be needed later on in the current page or globally.

  • Second, in every new development project, for an entire page or part of it, try to think about it before developing it. If you think part of it should be a component, create it.

  • Finally, if you’re not sure, don’t. Avoid contaminating your project with components that “might be useful later.” They can just sit there forever, and that’s not smart. Note that once you realize you should do this, it’s best to break it down to avoid compatibility and complexity with other parts of the project.


1. Use the vscode-FileHeader plug-in in VScode to generate header comment 2. // This is comment 2.2 Always leave a space before the end of a multi-line comment (to align the asterisks) /* */ 2.3 Do not write a comment on the start or end of a multi-line comment // bad /* Start end */ // good /* here is line 1 here is line 2 */ 2.5 If a piece of code has a function that is not implemented or needs to be improved, the "TODO" flag must be added. Function setOpacity(node, val) {node.style.opacity = val; } 3. Documentation Comments Documentation comments will appear in the API documentation in a predetermined format. It begins with a /, ends with a /, starts each line with a "" (all aligned with the first" "of the opening character), and leaves a space between the comment content and" ". 3.1 @ the module. The Core module provides the most basic and Core interface * @module Core */ 3.2@class. Class name @constructor */ @class must be used with @constructor or @static to mark non-static and static classes, respectively. /** * class NodeList * @constructor * @param {ArrayLike<Element>} Nodes initializes nodes */ 3.3 @method. Declare a function or class method /** * Method description * @method Method name * @for class name * @param {parameter type} Parameter Description * @return {return value type} Return value Description */ If @for is not specified, Indicates that this function is a global or module top-level function. When a function is static, you must add @static; When a function has arguments, it must use @param; When a function returns a value, it must use @return. /** * returns the subscript of the element * @method * @for NodeList * @param {Number} [I =0] at the specified position in the current collection. If negative, count backwards from the last Element of the set * @return {Element} specifies the Element */ - @param. Declare function arguments that must be used with @method. - The parameter format is used when: [Parameter name] - Parameter has default value [Parameter name = default value] 3.4@property. Declare class attribute /** * Attribute Description * @property {attribute type} Attribute name */Copy the code


Let go of that girl

This article source: open source China for reprint please contact the original author