Links to other specifications

RESTful Interface specifications

CSS specifications and naming

Git Usage Specification

1. Variable types and declarations

1.1 Variable Types

1.1.1 Basic Types

  • string
  • number
  • boolean
  • null
  • undefined
  • symbol
  • bigint

Symbol and BigInt are not polyfilled correctly. Therefore, it should not be used in environments [browsers] that do not support both types natively.

1.1.2 Complex Types

  • object
  • array
  • function

1.2 Variable Declaration

1.2.1 useconstAssignment, avoid usingvar

This ensures that you don’t change your initial values, as repeated references can lead to many bugs and code problems that are difficult to understand.

// bad
var a = 1
var b = 2

// good
const a = 1
const b = 2
Copy the code

1.2.2 If you need to reassign parameters, run theletAnd don’t usevar

// bad
var count = 1
if (true) {
  count += 1
}

// good
let count = 1
if (true) {
  count += 1
}
Copy the code

1.2.3 Use one for each variableconstlet

// bad
const items = getItems(),
    goSportsTeam = true,
    dragonball = 'z'

// good
const items = getItems()
const goSportsTeam = true
const dragonball = 'z'
Copy the code

1.constPut together,letPut together

// bad
let i
const items = getItems()
let dragonball
const goSportsTeam = true
let len

// good
const goSportsTeam = true
const items = getItems()
let dragonball
let i
let length
Copy the code

1.2.5 Declare variables where necessary, but in reasonable places

// bad
function checkName(hasName) {
  const name = getName()

  if (hasName === 'test') {
    return false
  }

  if (name === 'test') {
    return false
  }

  return name
}

// good
function checkName(hasName) {
  if (hasName === 'test') {
    return false
  }

  // Allocate as needed
  const name = getName()

  if (name === 'test') {
    return false
  }

  return name
}
Copy the code

1.2.6 Avoid assigning values in=Before/after line break. If your assignment exceeds the maximum length, wrap the value in parentheses before line break

// bad
const foo =
  superLongLongLongLongLongLongLongLongFunctionName()

// bad
const foo
  = 'superLongLongLongLongLongLongLongLongString'

// good
const foo = (
  superLongLongLongLongLongLongLongLongFunctionName()
)

// good
const foo = 'superLongLongLongLongLongLongLongLongString'
Copy the code

1.2.7 Unused variables or parameters after definition are not allowed

2. Basic type specifications

2.1 the Object

2.1.1 When creating objects, use the literal creation method

// bad
const item = new Object(a)// good
const item = {}
Copy the code

2.1.2 For objects defined in a single line, the last member does not end with a comma; An object defined on multiple lines with the last member ending in a comma

// bad
const a = { k1: v1, k2: v2, }
const b = {
  k1: v1,
  k2: v2
}

// good
const a = { k1: v1, k2: v2 }
const b = {
  k1: v1,
  k2: v2,
}
Copy the code

2.1.3 When creating an object with a dynamic attribute name, use the attribute expression definition

The last property name of the object obj, computed. In this case, it is best to use an attribute expression that defines the attribute along with other attributes when creating an OBJ. In this way, all attributes are defined in one place.

function getKey(k) {
  return `a key named ${k}`
}

// bad
const obj = {
  id: 5.name: 'San Francisco',
}
obj[getKey('attName')] = true

// good
const obj = {
  id: 5.name: 'San Francisco',
  [getKey('attName')]: true,}Copy the code

2.1.4 When creating object methods, use abbreviations

// bad
const atom = {
  value: 1.addValue: function (value) {
    returnatom.value + value; }}// good
const atom = {
  value: 1.// Object method
  addValue(value) {
    returnatom.value + value; }}Copy the code

2.1.5 Abbreviations are used when Writing Object Attribute Values

const lukeSkywalker = 'Luke Skywalker';

// bad
const obj = {
  lukeSkywalker: lukeSkywalker
}

// good
const obj = {
  lukeSkywalker
}
Copy the code

2.1.6 Abbreviate all attribute values at the beginning of the object declaration

const anakinSkywalker = 'Anakin Skywalker'
const lukeSkywalker = 'Luke Skywalker'

// bad
const obj = {
  episodeOne: 1.twoJediWalkIntoACantina: 2,
  lukeSkywalker,
  episodeThree: 3.mayTheFourth: 4,
  anakinSkywalker
}

// good
const obj = {
  lukeSkywalker,
  anakinSkywalker,
  episodeOne: 1.twoJediWalkIntoACantina: 2.episodeThree: 3.mayTheFourth: 4
}
Copy the code

In 2.1.7 key values, only those invalid identifiers are quoted' '

This approach is subjectively readable and optimizes code highlighting.

// bad
const bad = {
  'foo': 3.'bar': 4.'data-blah': 5
}

// good
const good = {
  foo: 3.bar: 4.'data-blah': 5
}
Copy the code

2.1.8 Objects should be static as far as possible. Once they are defined, new attributes should not be added at will. Use if adding attributes is unavoidableObject.assignmethods

// bad
const a = { x: 3 }
a.y = 4

// good
const a = { x: 3 }
Object.assign(a, { y: 4 })
Copy the code

2.1.9 Merging multiple objects or shallow copies of objects If no new object is returned, use this commandObject.assign(); To return a new object, use the extension operator (.)

// Return the initial object
const original = { a: 1.b: 2 }
Object.assign(original, { c: 3 })	// original { a: 1, b: 2, c: 3 }

// Return a new object
const original = { a: 1.b: 2 }
constnewOriginal = { ... original, ... {c: 3}}// newOriginal { a: 1, b: 2, c: 3 }
Copy the code

2.1.10 When obtaining properties specified by an object, use the object’s REST deconstruction operator (.)

const original = { a: 1.b: 2.c: 3 }

// rest assignment operator
const{ a, ... rest } = original// rest => { b: 2, c: 3 }
Copy the code

2.1.11 All configuration items should be grouped into one object and placed in the last parameter. Boolean values cannot be directly used as parameters

// bad
function divide(a, b, option = false ) {}// good
function divide(a, b, { option = false } = {}) {}Copy the code

2.2 Array

2.2.1 When creating an array, use the literal creation method

// bad
const items = new Array(a)// good
const items = []
Copy the code

2.2.2 When adding a value to an arrayArray.push()

const someStack = []

// bad
someStack[someStack.length] = 'abc'

// good
someStack.push('abc')
Copy the code

2.2.3 Using the Extended Operator when Copying arrays.)

// bad
const len = items.length
const itemsCopy = []
for (let i = 0; i < len; i++) {
  itemsCopy[i] = items[i]
}

// good
const itemsCopy = [...items]
Copy the code

2.2.4 To convert an iterable object (implementing the Iterator interface) into an array, use the extension operator (.)

/ / the arguments object
function foo() {
  const args = [...arguments]
}
Copy the code

2.2.5 Is used when converting an array-like object into an arrayArray.frommethods

const foo = document.querySelectorAll('.foo')
const arrLike = { 0: 'foo'.1: 'bar'.2: 'baz'.length: 3 }

const nodes = Array.from(foo)
const arr = Array.from(arrLike)
Copy the code

2.2.6 Need to convert to array for map traversal, useArray.fromRather than.The operator

This avoids creating a temporary array.

// bad
const baz = [...foo].map(bar)

// good
const baz = Array.from(foo, bar)
Copy the code

2.2.7 Using return statements in callback functions of array methods

If the function body consists of a statement that returns an expression, and the expression has no side effects, you can omit the return.

The good function has multiple statements
[1.2.3].map((x) = > {
  const y = x + 1
  return x * y
});


The good function has only one statement
[1.2.3].map(x= > x + 1);


// Bad returns no value, acc becomes undefined after the first iteration
[[0.1], [2.3], [4.5]].reduce((acc, item, index) = > {
  const flatten = acc.concat(item)
  acc[index] = flatten
})

// good
[[0.1], [2.3], [4.5]].reduce((acc, item, index) = > {
  const flatten = acc.concat(item)
  acc[index] = flatten
  return flatten
})


// bad
inbox.filter((msg) = > {
  const { subject, author } = msg
  if (subject === 'Mockingbird') {
    return author === 'Harper Lee'
  } else {
    return false}})// good is easy to write
inbox.filter((msg) = > {
  const { subject, author } = msg;
  if (subject === 'Mockingbird') {
    return author === 'Harper Lee'
  }

  return false
})
Copy the code

2.2.8 If an array has many rows in the array[And after]Line breaks before

// bad
const arr = [
  [0.1], [2.3], [4.5]]const objectInArray = [{
  id: 1}, {id: 2,}]const numberInArray = [
  1.2,]// good
const arr = [[0.1], [2.3], [4.5]]

const objectInArray = [
  {
    id: 1}, {id: 2,},]const numberInArray = [
  1.2,]Copy the code

2.3 the String

2.3.1 Static strings use single quotation marks instead of double quotation marks. Dynamic strings use reverse quotation marks

// bad
const a = "foobar"
const b = 'foo' + a + 'bar'

// good
const a = 'foobar'
const b = `foo${a}bar`
Copy the code

2.3.2 Strings of more than 100 characters should not be concatenated with strings

Broken strings look bad and make the code harder to search.

// bad
const errorMessage = 'This is a super long error that was thrown because \ of Batman. When you stop to think about how Batman had anything to  do \ with this, you would get nowhere \ fast.'

// bad
const errorMessage = 'This is a super long error that was thrown because ' +
  'of Batman. When you stop to think about how Batman had anything to do ' +
  'with this, you would get nowhere fast.'

// good
const errorMessage = 'This is a super long error that was thrown because of Batman. When you stop to think about how Batman had anything to do with this, you would get nowhere fast.'
Copy the code

2.3.3 Do not use in stringseval()

Do not use unnecessary escape characters

Backslashes are not readable, so use them only when you must

// bad
const foo = '\'this\' \i\s \"quoted\"'

// good
const foo = '\'this\' is "quoted"'

//best
const foo = `my name is '${name}'`
Copy the code

2.4 the Function

2.4.1 Using Default Values Syntax Sets the default values of function parameters and puts the default parameter assignment last

// bad
function handleThings(opts) {
  opts = opts || {}
}

// good
function handleThings(opts = {}) {
  // ...
}
Copy the code

Do not use 2.4.2argumentsVariable, using the REST operator (.) instead of

Because rest operators explicitly indicate that you want to get arguments, and arguments is an array-like object, rest operators can provide a real array.

// bad
function concatenateAll() {
  const args = Array.prototype.slice.call(arguments);
  return args.join(' ')}// good
function concatenateAll(. args) {
  return args.join(' ')}Copy the code

2.4.3 iniforforIn block statements, use function expressions instead of function declarations

In ECMA-262 a block is defined as a series of statements. But a function declaration is not a statement, a function expression is.

// bad
if (currentUser) {
  function test() {
    console.log('Nope.')}}// good
let test
if (currentUser) {
  test = () = > {
    console.log('Yup.')}}Copy the code

2.4.4 don’t useargumentsNamed parameters that take precedence over those inherent in each function scopeargumentsObject, which causes the function to be nativeargumentsValues are covered

// bad
function foo(name, options, arguments) {
  // ...
}

// good
function foo(name, options, args) {
  // ...
}
Copy the code

2.4.5 The function signature must contain Spaces

// bad
const f = function(){}
const g = function (){}
const h = function() {}

// good
const x = function () {}
const y = function a() {}
Copy the code

2.4.6 Do not Modify parameters

Do not modify the data structure of the parameter object, leaving the original value and data structure of the parameter.

// bad
function f1(obj) {
  obj.key = 1
}

// good
function f2(obj) {
  const key = obj.hasOwnProperty('key')? obj.key :1
}
Copy the code

2.4.7 Do not reassign parameters

// bad
function f1(a) {
  a = 1
  // ...
}

function f2(a) {
  if(! a) { a =1; }
  // ...
}

// good
function f3(a) {
  const b = a || 1
  // ...
}

function f4(a = 1) {
  // ...
}
Copy the code

2.5 Arrow Function

2.5.1 When anonymous functions are used as parameters, use arrow functions instead

This is cleaner and binds this to the external scope.

// 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)
Copy the code

2.5.2 When an expression involves multiple lines, enclose it in parentheses

More readable.

// bad
['get'.'post'.'put'].map(httpMethod= > Object.prototype.hasOwnProperty.call(
    httpMagicObjectWithAVeryLongName,
    httpMethod
  )
)

// good
['get'.'post'.'put'].map(httpMethod= > (
  Object.prototype.hasOwnProperty.call(
    httpMagicObjectWithAVeryLongName,
    httpMethod
  )
))
Copy the code

2.5.3 Write the execute now function in the form of an arrow function wrapped in parentheses

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.

(() = > {
  console.log('Welcome')
}())
Copy the code

2.5.4 Use arrow function insteadFunction.prototype.bindInstead of using self/_this/that to bind this

// bad
const self = this
const boundMethod = function(. params) {
  return method.apply(self, params)
}

// good
const boundMethod = (. params) = > method.apply(this, params)
Copy the code

2.5.5 When your function has only one argument and the function body has no braces, remove the parentheses, otherwise the arguments are always in parentheses

// bad
[1.2.3].map((x) = > x * x)

// good
[1.2.3].map(x= > x * x)

// good
[1.2.3].map(number= > (
  `A long string with the ${number}It's so long that we don't want It to take up space on the. Map line! `
))

// bad
[1.2.3].map(x= > {
  const y = x + 1;
  return x * y;
})

// good
[1.2.3].map((x) = > {
  const y = x + 1;
  return x * y;
})
Copy the code

2.5.6 Avoiding Arrow Functions (= >) and the comparison operator (< =, > =Confused)

// bad
const itemHeight = (item) = > item.height <= 256 ? item.largeSize : item.smallSize

// bad
const itemHeight = (item) = > item.height >= 256 ? item.largeSize : item.smallSize

// good
const itemHeight = (item) = > (item.height <= 256 ? item.largeSize : item.smallSize)

// good
const itemHeight = (item) = > {
  const { height, largeSize, smallSize } = item
  return height <= 256 ? largeSize : smallSize
}
Copy the code

2.5.7 Constrain the position of the function body in implicit return, written after the arrow

// bad
(foo) =>
  bar;

(foo) = >
  (bar);

// good
(foo) = > bar;
(foo) = > (bar);
(foo) = > (
   bar
)
Copy the code

2.6 the Module

2.6.1 useimportreplacerequire

The Module syntax is the standard way to write JavaScript modules.

// bad
const moduleA = require('moduleA')
const func1 = moduleA.func1
const func2 = moduleA.func2

// good
import { func1, func2 } from 'moduleA'
Copy the code

2.6.2 Only one pathimportAt a time

// bad
import foo from 'foo'
/ /... Some other imports... //
import { named1, named2 } from 'foo'

// good
import foo, { named1, named2 } from 'foo'

// good
import foo, {
  named1,
  named2,
} from 'foo'
Copy the code

2.6.3 to useexportreplacemodule.exports

// bad
module.exports = Breadcrumbs

// good
export default Breadcrumbs
Copy the code

2.6.4 Do not use wildcards in module input*

This ensures that you have an export default in your module.

// bad
import * as myObject from './importModule'

// good
import myObject from './importModule'
Copy the code

2.6.5 If the module outputs a function by default, the first letter of the function name should be lowercase

function makeStyleGuide() {}export default makeStyleGuide
Copy the code

2.6.6 If the module outputs an object by default, the first letter of the object name should be capitalized

const StyleGuide = {
  es6: {}}export default StyleGuide
Copy the code

2.6.7 Do not export variable quantities

Change is usually something to avoid, especially if you want to output mutable bindings. In general, we should derive constants.

// bad
let foo = 3
export { foo }

// good
const foo = 3
export { foo }
Copy the code

2.6.8 In a single export module, useexport defaultbetter

Encourage more files, do one thing per file and export for better readability and maintainability.

// bad
export function foo() {}

// good
export default function foo() {}
Copy the code

2.6.9 importBefore all other statements

// bad
import foo from 'foo'
foo.init()

import bar from 'bar'

// good
import foo from 'foo'
import bar from 'bar'

foo.init()
Copy the code

2.7 deconstruction

2.7.1 Destructive assignment is preferred for function parameters that are members of objects

// bad
function getFullName(obj) {
  const firstName = obj.firstName;
  const lastName = obj.lastName;
}

// good
function getFullName(obj) {
  const { firstName, lastName } = obj;
}

// best
function getFullName({ firstName, lastName }) {}Copy the code

2.7.2 When Assigning values to Variables using Array Members, Destruct Assignment is preferred (When the array length is small)

const arr = [1.2.3.4]

// bad
const first = arr[0]
const second = arr[1]

// good
const [first, second] = arr
Copy the code

2.7.3 If a function returns multiple values, object deconstruction assignment is preferred over array deconstruction assignment

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)
Copy the code

2.7.4 Deconstruction is used when two numbers exchange values

let a1 = 1
let a2 = 2;

[a1, a2] = [a2, a1]
Copy the code

2.8 the Class

2.8.1 always useClassReplace the needprototypeIn the operation. And the use ofextendsImplementation inheritance

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
  }
}
Copy the code

2.8.2 Class methods should be used unless a specific non-static method is required by an external library or frameworkthisOr static methods, as an instance method should indicate that it behaves differently depending on the receiver’s attributes

// bad
class Foo {
  bar() {
    console.log('bar'); }}// good-this is used
class Foo {
  bar() {
    console.log(this.bar); }}// Good-constructor does not have to use this
class Foo {
  constructor() {
    // ...}}// good - Static methods do not need to use this
class Foo {
  static bar() {
    console.log('bar'); }}Copy the code

2.9 Iterators & Generators

2.9.1 Do not use traversers, use JavaScript advanced functions insteadfor-in,for-of

Using these iterative methods of arrays: map()/every()/filter()/find()/findIndex()/reduce()/some() /… “, use the Object methods Object.keys()/object.values ()/object.entries () to generate an array that will traverse the Object.

const numbers = [1.2.3.4.5]

// bad
let sum = 0
for (let num of numbers) {
  sum += num
}
sum === 15

// good
let sum = 0
numbers.forEach(num= > sum += num)
sum === 15

// best (use the functional force)
const sum = numbers.reduce((total, num) = > total + num, 0);
sum === 15

// bad
const increasedByOne = []
for (let i = 0; i < numbers.length; i++) {
  increasedByOne.push(numbers[i] + 1)}// good
const increasedByOne = []
numbers.forEach(num= > increasedByOne.push(num + 1))

// best (keeping it functional)
const increasedByOne = numbers.map(num= > num + 1)
Copy the code

2.9.2 Do not use generator

2.10 attributes

2.10.1 Use dot notation when accessing properties.

const luke = {
  jedi: true.age: 28,}// bad
const isJedi = luke['jedi']

// good
const isJedi = luke.jedi
Copy the code

2.10.2 Square brackets are used when the obtained attribute is a variable[]take

const luke = {
  jedi: true.age: 28,}function getProp(prop) {
  return luke[prop]
}

const isJedi = getProp('jedi')
Copy the code

2.10.3 Power operators are used for power operations支那

// bad
const binary = Math.pow(2.10)

// good
const binary = 2支那10
Copy the code

2.11 the operator

2.11.1 There is no semicolon at the end of a sentence except in the following cases

  • When a line of code is(At the beginning, a semicolon is added to avoid parsing errors.
function say() {
  console.log('hello world')
}

;say()

;(function () {
  console.log('hello')
})()
Copy the code
  • When a line of code is[At the beginning, a semicolon is added to avoid parsing errors.
; ['apple'.'banana'].forEach(function (item) {
	console.log(item)
 })
Copy the code
  • When a line of code begins with ‘, a semicolon is added to avoid parsing errors.
;`hello`.toString()
Copy the code

2.11.2 Use curly braces to create a syntax declaration area in case and default clauses

// bad
switch (foo) {
  case 1:
    let x = 1
    break
  case 2:
    const y = 2
    break
  case 3:
    function f() {
      // ...
    }
    break
  default:
    class C {}}// good
switch (foo) {
  case 1: {
    let x = 1
    break
  }
  case 2: {
    const y = 2
    break
  }
  case 3: {
    function f() {
      // ...
    }
    break
  }
  case 4:
    bar()
    break
  default: {
    class C {}}}Copy the code

2.11.3 Ternary expressions should not be nested and are usually single-line expressions

// bad
const foo = maybe1 > maybe2
  ? "bar"
  : value1 > value2 ? "baz" : null
 
// better
const maybeNull = value1 > value2 ? 'baz' : null
 
const foo = maybe1 > maybe2
  ? 'bar'
  : maybeNull
 
// best
const maybeNull = value1 > value2 ? 'baz' : null
 
const foo = maybe1 > maybe2 ? 'bar' : maybeNull
Copy the code

2.11.4 Avoid unnecessary ternary expressions

// bad
const foo = a ? a : b
const bar = c ? true : false
const baz = c ? false : true
 
// good
const foo = a || b
constbar = !! cconstbaz = ! cCopy the code

2.11.5 Mix these operators with parentheses. Only if the standard arithmetic operator (+.-.*, & /), and they can be enclosed without parentheses when their priority is obvious

// bad
const foo = a && b < 0 || c > 0 || d + 1= = =0
 
// bad
const bar = a ** b - 5 % d
 
// bad
/ / others fall into (a | | b) & c confused
if (a || b && c) {
  return d
}
 
// good
const foo = (a && b < 0) || c > 0 || (d + 1= = =0)
 
// good
const bar = (a ** b) - (5 % d)
 
// good
if (a || (b && c)) {
  return d
}
 
// good
const bar = a + b / c * d
Copy the code

2.12 the code block

2.12.1 Wrapping Multi-line Code Blocks in Braces

// bad
if (test)
  return false
 
// good
if (test) return false
 
// good
if (test) {
  return false
}
 
// bad
function foo() { return false }
 
// good
function bar() {
  return false
}
Copy the code

2.12.2 The else and if closing braces must be on the same line

// bad
if (test) {
  thing1()
  thing2()
}
else {
  thing3()
}
 
// good
if (test) {
  thing1()
  thing2()
} else {
  thing3()
}
Copy the code

2.12.3 Return in the IF statement

If the return in an if statement always needs to be returned with a return, then the else does not need to be written. The if block contains a return, and the else if block after it contains a return, so you can split a return into multiple if blocks.

// bad
function foo() {
  if (x) {
    return x
  } else {
    return y
  }
}

// bad
function cats() {
  if (x) {
    return x
  } else if (y) {
    return y
  }
}

// bad
function dogs() {
  if (x) {
    return x
  } else {
    if (y) {
      return y
    }
  }
}

// good
function foo() {
  if (x) {
    return x
  }

  return y
}

// good
function cats() {
  if (x) {
    return x
  }

  if (y) {
    return y
  }
}

// good
function dogs(x) {
  if (x) {
    if (z) {
      return y
    }
  } else {
    return z
  }
}
Copy the code

2.13 annotations

2.13.1 Multi-Line Comments Using /**… * /

// bad
// make() returns a new element
// based on the passed in tag name
//
// @param {String} tag
// @return {Element} element
function make(tag) {

  // ...

  return element
}

// good
/** * make() returns a new element * based on the passed-in tag name */
function make(tag) {

  // ...

  return element
}
Copy the code

2.13.2 Single-line comments//

Place a single line comment on top of the commented area. If the comment is not on the first line, the comment is preceded by a blank line.

// bad
const active = true  // is current tab

// good
// is current tab
const active = true

// bad
function getType() {
  console.log('fetching type... ');
  // set the default type to 'no type'
  const type = this._type || 'no type'

  return type
}

// good
function getType() {
  console.log('fetching type... ')

  // set the default type to 'no type'
  const type = this._type || 'no type'

  return type
}

// also good
function getType() {
  // set the default type to 'no type'
  const type = this._type || 'no type'

  return type
}
Copy the code

2.13.3 Spaces at the beginning of comments

All comments start with a blank space for easy reading.

// bad
//is current tab
const active = true

// good
// is current tab
const active = true

// bad
/** *make() returns a new element *based on the passed-in tag name */
function make(tag) {

  // ...

  return element
}

// good
/** * make() returns a new element * based on the passed-in tag name */
function make(tag) {

  // ...

  return element
}
Copy the code

2.14 the blank space

2.14.1 Use two Spaces for TAB

// bad
function foo() {,,,,const name
}

// bad
function bar() {,const name
}

// good
function baz() {,,const name
}
Copy the code

2.14.2 Leave one space before braces

// bad
function test(){
  console.log('test')}// good
function test() {
  console.log('test')}// bad
dog.set('attr', {age: '1 year'.breed: 'Bernese Mountain Dog',})// good
dog.set('attr', {
  age: '1 year'.breed: 'Bernese Mountain Dog',})Copy the code

2.14.3 In Control Statements (if.while, etc.), one space before the parentheses

When a function is called and defined, there is no space between the argument list and the function name.

// bad
if(isJedi) {
  fight ()
}

// good
if (isJedi) {
  fight()
}

// bad
function fight () {
  console.log ('Swooosh! ')}// good
function fight() {
  console.log('Swooosh! ')}Copy the code

2.14.4 Separate operators with Spaces

// bad
const x=y+5

// good
const x = y + 5
Copy the code

2.14.5 A blank line after a code block and before the next statement

// bad
if (foo) {
  return bar
}
return baz

// good
if (foo) {
  return bar
}

return baz

// bad
const obj = {
  foo(){},bar(){},}return obj

// good
const obj = {
  foo(){},bar(){},}return obj

// bad
const arr = [
  function foo() {},function bar() {},]return arr

// good
const arr = [
  function foo() {},function bar() {},]return arr
Copy the code

2.14.6 Do not fill blocks with blank lines

// bad
function bar() {

  console.log(foo)

}

// also bad
if (baz) {

  console.log(qux)
} else {
  console.log(foo)

}

// good
function bar() {
  console.log(foo)
}

// good
if (baz) {
  console.log(qux)
} else {
  console.log(foo)
}
Copy the code

2.14.7 Spaces must be added in curly braces

// bad
const foo = {clark: 'kent'}

// good
const foo = { clark: 'kent' }
Copy the code

2.14.8 There must be Spaces between key values in literal attributes of objects

// bad
var obj = { "foo" : 42 }
var obj2 = { "foo":42 }

// good
var obj = { "foo": 42 }
Copy the code

2.15 Type Conversion

2.15.1 Converting to a Boolean value

const age = 0

// bad
const hasAge = new Boolean(age)

// good
const hasAge = Boolean(age)

// best
consthasAge = !! ageCopy the code

2.15.2 Converting to Number

Number is preferred because parseInt is often used to convert strings to cardinality.

const inputValue = '4'

// bad
const val = new Number(inputValue)

// bad
const val = +inputValue

// bad
const val = inputValue >> 0

// bad
const val = parseInt(inputValue)

// good
const val = Number(inputValue)

// good
const val = parseInt(inputValue, 10)
Copy the code

3. Basic naming conventions

3.1 JavaScript general naming

3.1.1 Avoid one-letter names and make your names descriptive

// bad
function q() {
  // ...
}

// good
function query() {
  // ...
}
Copy the code

3.1.2 Naming objects, functions and instances in small camel shape

// bad
const OBJEcttsssss = {}
const this_is_my_object = {}
function c() {}

// good
const thisIsMyObject = {}
function thisIsMyFunction() {}
Copy the code

3.1.3 Naming classes in big camel shape

// bad
function user(options) {
  this.name = options.name
}

const bad = new user({
  name: 'nope',})// good
class User {
  constructor(options) {
    this.name = options.name
  }
}

const good = new User({
  name: 'yup',})Copy the code

3.1.4 Do not use leading or trailing underscores

The leading underline usually means “private” in concept

// bad
this.__firstName__ = 'Panda'
this.firstName_ = 'Panda'
this._firstName = 'Panda'

// good
this.firstName = 'Panda'
Copy the code

3.1.5 System constants are named in all uppercase letters, with words connected by _ underscores

Make sure it’s const, make sure it can’t be changed.

// bad
const auditStatus = 'failed'

// good
const AUDIT_STATUS = 'failed'
Copy the code

3.2 Vue general naming

3.2.1 Component name Multiple words

Component names should always be multiple words and should always be named (except for the root component App and Vue built-in components like
and < Component >) using PascalCase naming.

The component file name must be the same as the component name.

// bad
Vue.component('Detail', {
  // ...
})

export default {
  name: 'Detail'.// ...
}


// good
Vue.component('NewsDetail', {
  // ...
})

export default {
  name: 'NewsDetail'.// ...
}
Copy the code

3.2.2 Basic Component names

Underlying components that apply a specific style and convention (that is, components that present classes without logic or stateless) should all begin with a specific prefix, such as Base.

// bad
components/
|- MyButton.vue
|- VueTable.vue
|- Icon.vue

// good
components/
|- BaseButton.vue
|- BaseTable.vue
|- BaseIcon.vue
Copy the code

3.2.3 Singleton Component name

Components that should only have a single active instance should be named with The prefix to indicate their uniqueness. This does not mean that components can only be used on a single page, but only once per page. These components never accept any prop because they are customized for your application, not their context in your application. If you find it necessary to add prop, that means it is actually a reusable component that is currently only used once per page.

// bad
components/
|- Heading.vue
|- MySidebar.vue

// good
components/
|- TheHeading.vue
|- TheSidebar.vue
Copy the code

3.2.4 Tightly coupled component names

Child components that are tightly coupled to the parent component should be named prefixed with the parent component name. If a component only makes sense in the context of a parent component, this relationship should be reflected in its name. Because editors usually organize files alphabetically, doing so puts related files together.

// bad
components/
|- TodoList.vue
|- TodoItem.vue
|- TodoButton.vue
|- NavigationForSearchSidebar.vue

// good
components/
|- TodoList.vue
|- TodoListItem.vue
|- TodoListItemButton.vue
|- SearchSidebar.vue
|- SearchSidebarNavigation.vue
Copy the code

3.2.5 Word order in component names

Component names should start with high-level (usually generically described) words and end with descriptive modifiers.

// bad
components/
|- ClearSearchButton.vue
|- ExcludeFromSearchInput.vue
|- LaunchOnStartupCheckbox.vue
|- RunSearchButton.vue

// good
components/
|- SearchButtonClear.vue
|- SearchButtonRun.vue
|- SearchInputQuery.vue
|- SearchInputExcludeGlob.vue
Copy the code

3.2.6 Using components in templates

Kebab-case is used when using components in templates.

<template> <div> <base-component></base-component> </div> <template> import BaseComponent from '... ' <script> components: { BaseComponent } </script>Copy the code

3.2.7 Full word component names

Component names should tend to be full words rather than abbreviations, which can provide good clarity.

// bad
components/
|- SdSettings.vue
|- UProfOpts.vue

// good
components/
|- StudentDashboardSettings.vue
|- UserProfileOptions.vue
Copy the code

3.2.8 Prop

When declaring prop, it should always be named camelCase, and kebab-case should always be used in templates and JSX.

Because in JavaScript it’s more natural to have camelCase and in HTML it’s kebab-case.

// bad
props: {
  'greeting-text': String
}
<WelcomeMessage greetingText="hi"/>

// good
props: {
  greetingText: String
}
<WelcomeMessage greeting-text="hi"/>
Copy the code