命名規(guī)范
1.組件名遵從駝峰形式,第一個(gè)字母大寫
2.方法名、參數(shù)名、成員變量、局部變量遵從駝峰形式,第一個(gè)字母必須小寫
3.常量命名全部大寫,單詞間用下劃線隔開,力求語義表達(dá)完整清楚,不要嫌名字長;
4.私有方法,方法名前面加下劃線
注釋
1.公共組件使用說明
2.各組件中重要函數(shù)或者類說明
3.復(fù)雜的業(yè)務(wù)邏輯處理說明
4.特殊情況的代碼處理說明,對于代碼中特殊用途的變量、存在臨界值、使用了某種算法或思路等需要進(jìn)行注釋描述
eslint編碼規(guī)范
-
使用兩個(gè)空格進(jìn)行縮進(jìn)。
eslint:
indentfunction hello (name) { console.log('hi', name) } -
除需要轉(zhuǎn)義的情況外,字符串統(tǒng)一使用單引號(hào)。
eslint:
quotesconsole.log('hello there') $("<div class='box'>") -
不要定義未使用的變量。
eslint:
no-unused-varsfunction myFunction () { var result = something() // ? avoid } -
關(guān)鍵字后面加空格。
eslint:
keyword-spacingif (condition) { ... } // ? ok if(condition) { ... } // ? avoid -
函數(shù)聲明時(shí)括號(hào)與函數(shù)名間加空格。
eslint:
space-before-function-parenfunction name (arg) { ... } // ? ok function name(arg) { ... } // ? avoid run(function () { ... }) // ? ok run(function() { ... }) // ? avoid -
始終使用
===替代==。
例外:obj == null可以用來檢查null || undefined。eslint:
eqeqeqif (name === 'John') // ? ok if (name == 'John') // ? avoidif (name !== 'John') // ? ok if (name != 'John') // ? avoid -
字符串拼接操作符 (Infix operators) 之間要留空格。
eslint:
space-infix-ops// ? ok var x = 2 var message = 'hello, ' + name + '!'// ? avoid var x=2 var message = 'hello, '+name+'!' -
逗號(hào)后面加空格。
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) { ... } -
else 關(guān)鍵字要與花括號(hào)保持在同一行。
eslint:
brace-style// ? ok if (condition) { // ... } else { // ... }// ? avoid if (condition) { // ... } else { // ... } -
多行 if 語句的的括號(hào)不能省。
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') -
不要丟掉異常處理中
err參數(shù)。eslint:
handle-callback-err// ? ok run(function (err) { if (err) throw err window.alert('done') })// ? avoid run(function (err) { window.alert('done') }) -
使用瀏覽器全局變量時(shí)加上
window.前綴。
Exceptions are:document,consoleandnavigator.eslint:
no-undefwindow.alert('hi') // ? ok -
不允許有連續(xù)多行空行。
eslint:
no-multiple-empty-lines// ? ok var value = 'hello world' console.log(value)// ? avoid var value = 'hello world' console.log(value) -
對于三元運(yùn)算符
?和:與他們所負(fù)責(zé)的代碼處于同一行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' -
每個(gè) var 關(guān)鍵字單獨(dú)聲明一個(gè)變量。
eslint:
one-var// ? ok var silent = true var verbose = true // ? avoid var silent = true, verbose = true // ? avoid var silent = true, verbose = true -
條件語句中賦值語句使用括號(hào)包起來。這樣使得代碼更加清晰可讀,而不會(huì)認(rèn)為是將條件判斷語句的全等號(hào)(
===)錯(cuò)寫成了等號(hào)(=)。eslint:
no-cond-assign// ? ok while ((m = text.match(expr))) { // ... } // ? avoid while (m = text.match(expr)) { // ... } -
單行代碼塊兩邊加空格。
eslint:
block-spacingfunction foo () {return true} // ? avoid function foo () { return true } // ? ok -
對于變量和函數(shù)名統(tǒng)一使用駝峰命名法。
eslint:
camelcasefunction my_function () { } // ? avoid function myFunction () { } // ? ok var my_var = 'hello' // ? avoid var myVar = 'hello' // ? ok -
不允許有多余的行末逗號(hào)。
eslint:
comma-danglevar obj = { message: 'hello', // ? avoid } -
始終將逗號(hào)置于行末。
eslint:
comma-stylevar obj = { foo: 'foo' ,bar: 'bar' // ? avoid } var obj = { foo: 'foo', bar: 'bar' // ? ok } -
點(diǎn)號(hào)操作符須與屬性需在同一行。
eslint:
dot-locationconsole. log('hello') // ? avoid console .log('hello') // ? ok -
文件末尾留一空行。
elint:
eol-last -
函數(shù)調(diào)用時(shí)標(biāo)識(shí)符與括號(hào)間不留間隔。
eslint:
func-call-spacingconsole.log ('hello') // ? avoid console.log('hello') // ? ok -
鍵值對當(dāng)中冒號(hào)與值之間要留空白。
eslint:
key-spacingvar obj = { 'key' : 'value' } // ? avoid var obj = { 'key' :'value' } // ? avoid var obj = { 'key':'value' } // ? avoid var obj = { 'key': 'value' } // ? ok -
構(gòu)造函數(shù)要以大寫字母開頭。
eslint:
new-capfunction animal () {} var dog = new animal() // ? avoid function Animal () {} var dog = new Animal() // ? ok -
無參的構(gòu)造函數(shù)調(diào)用時(shí)要帶上括號(hào)。
eslint:
new-parensfunction Animal () {} var dog = new Animal // ? avoid var dog = new Animal() // ? ok -
對象中定義了存值器,一定要對應(yīng)的定義取值器。
eslint:
accessor-pairsvar person = { set name (value) { // ? avoid this.name = value } } var person = { set name (value) { this.name = value }, get name () { // ? ok return this.name } } -
子類的構(gòu)造器中一定要調(diào)用
supereslint:
constructor-superclass Dog { constructor () { super() // ? avoid } } class Dog extends Mammal { constructor () { super() // ? ok } } -
使用數(shù)組字面量而不是構(gòu)造器。
eslint:
no-array-constructorvar nums = new Array(1, 2, 3) // ? avoid var nums = [1, 2, 3] // ? ok -
避免使用
arguments.callee和arguments.caller。eslint:
no-callerfunction foo (n) { if (n <= 0) return arguments.callee(n - 1) // ? avoid } function foo (n) { if (n <= 0) return foo(n - 1) } -
避免對類名重新賦值。
eslint:
no-class-assignclass Dog {} Dog = 'Fido' // ? avoid -
避免修改使用
const聲明的變量。eslint:
no-const-assignconst score = 100 score = 125 // ? avoid -
避免使用常量作為條件表達(dá)式的條件(循環(huán)語句除外)。
eslint:
no-constant-conditionif (false) { // ? avoid // ... } if (x === 0) { // ? ok // ... } while (true) { // ? ok // ... } -
正則中不要使用控制符。
eslint:
no-control-regexvar pattern = /\x1f/ // ? avoid var pattern = /\x20/ // ? ok -
不要使用
debugger。eslint:
no-debuggerfunction sum (a, b) { debugger // ? avoid return a + b } -
不要對變量使用
delete操作。eslint:
no-delete-varvar name delete name // ? avoid -
不要定義冗余的函數(shù)參數(shù)。
eslint:
no-dupe-argsfunction sum (a, b, a) { // ? avoid // ... } function sum (a, b, c) { // ? ok // ... } -
類中不要定義冗余的屬性。
eslint:
no-dupe-class-membersclass Dog { bark () {} bark () {} // ? avoid } -
對象字面量中不要定義重復(fù)的屬性。
eslint:
no-dupe-keysvar user = { name: 'Jane Doe', name: 'John Doe' // ? avoid } -
switch語句中不要定義重復(fù)的case分支。eslint:
no-duplicate-caseswitch (id) { case 1: // ... case 1: // ? avoid } -
同一模塊有多個(gè)導(dǎo)入時(shí)一次性寫完。
eslint:
no-duplicate-importsimport { myFunc1 } from 'module' import { myFunc2 } from 'module' // ? avoid import { myFunc1, myFunc2 } from 'module' // ? ok -
正則中不要使用空字符。
eslint:
no-empty-character-classconst myRegex = /^abc[]/ // ? avoid const myRegex = /^abc[a-z]/ // ? ok -
不要解構(gòu)空值。
eslint:
no-empty-patternconst { a: {} } = foo // ? avoid const { a: { b } } = foo // ? ok -
不要使用
eval()。eslint:
no-evaleval( "var result = user." + propName ) // ? avoid var result = user[propName] // ? ok -
catch中不要對錯(cuò)誤重新賦值。eslint:
no-ex-assigntry { // ... } catch (e) { e = 'new value' // ? avoid } try { // ... } catch (e) { const newVal = 'new value' // ? ok } -
不要擴(kuò)展原生對象。
eslint:
no-extend-nativeObject.prototype.age = 21 // ? avoid -
避免多余的函數(shù)上下文綁定。
eslint:
no-extra-bindconst name = function () { getName() }.bind(user) // ? avoid const name = function () { this.getName() }.bind(user) // ? ok -
避免不必要的布爾轉(zhuǎn)換。
eslint:
no-extra-boolean-castconst result = true if (!!result) { // ? avoid // ... } const result = true if (result) { // ? ok // ... } -
不要使用多余的括號(hào)包裹函數(shù)。
eslint:
no-extra-parensconst myFunc = (function () { }) // ? avoid const myFunc = function () { } // ? ok -
switch一定要使用break來將條件分支正常中斷。eslint:
no-fallthroughswitch (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() } -
不要省去小數(shù)點(diǎn)前面的0。
eslint:
no-floating-decimalconst discount = .5 // ? avoid const discount = 0.5 // ? ok -
避免對聲明過的函數(shù)重新賦值。
eslint:
no-func-assignfunction myFunc () { } myFunc = myOtherFunc // ? avoid -
不要對全局只讀對象重新賦值。
eslint:
no-global-assignwindow = {} // ? avoid -
注意隱式的
eval()。eslint:
no-implied-evalsetTimeout("alert('Hello world')") // ? avoid setTimeout(function () { alert('Hello world') }) // ? ok -
嵌套的代碼塊中禁止再定義函數(shù)。
eslint:
no-inner-declarationsif (authenticated) { function setAuthUser () {} // ? avoid } -
不要向
RegExp構(gòu)造器傳入非法的正則表達(dá)式。eslint:
no-invalid-regexpRegExp('[a-z') // ? avoid RegExp('[a-z]') // ? ok -
不要使用非法的空白符。
eslint:
no-irregular-whitespacefunction myFunc () /*<NBSP>*/{} // ? avoid -
禁止使用
__iterator__。eslint:
no-iteratorFoo.prototype.__iterator__ = function () {} // ? avoid -
外部變量不要與對象屬性重名。
eslint:
no-label-varvar score = 100 function game () { score: 50 // ? avoid } -
不要使用標(biāo)簽語句。
eslint:
no-labelslabel: while (true) { break label // ? avoid } -
不要書寫不必要的嵌套代碼塊。
eslint:
no-lone-blocksfunction myFunc () { { // ? avoid myOtherFunc() } } function myFunc () { myOtherFunc() // ? ok } -
不要混合使用空格與制表符作為縮進(jìn)。
eslint:
no-mixed-spaces-and-tabs -
除了縮進(jìn),不要使用多個(gè)空格。
eslint:
no-multi-spacesconst id = 1234 // ? avoid const id = 1234 // ? ok -
不要使用多行字符串。
eslint:
no-multi-strconst message = 'Hello \ world' // ? avoid -
new創(chuàng)建對象實(shí)例后需要賦值給變量。eslint:
no-newnew Character() // ? avoid const character = new Character() // ? ok -
禁止使用
Function構(gòu)造器。eslint:
no-new-funcvar sum = new Function('a', 'b', 'return a + b') // ? avoid -
禁止使用
Object構(gòu)造器。eslint:
no-new-objectlet config = new Object() // ? avoid -
禁止使用
new require。eslint:
no-new-requireconst myModule = new require('my-module') // ? avoid -
禁止使用
Symbol構(gòu)造器。eslint:
no-new-symbolconst foo = new Symbol('foo') // ? avoid -
禁止使用原始包裝器。
eslint:
no-new-wrappersconst message = new String('hello') // ? avoid -
不要將全局對象的屬性作為函數(shù)調(diào)用。
eslint:
no-obj-callsconst math = Math() // ? avoid -
不要使用八進(jìn)制字面量。
eslint:
no-octalconst num = 042 // ? avoid const num = '042' // ? ok -
字符串字面量中也不要使用八進(jìn)制轉(zhuǎn)義字符。
eslint:
no-octal-escapeconst copyright = 'Copyright \251' // ? avoid -
使用
__dirname和__filename時(shí)盡量避免使用字符串拼接。eslint:
no-path-concatconst pathToFile = __dirname + '/app.js' // ? avoid const pathToFile = path.join(__dirname, 'app.js') // ? ok -
使用
getPrototypeOf來替代__proto__。eslint:
no-protoconst foo = obj.__proto__ // ? avoid const foo = Object.getPrototypeOf(obj) // ? ok -
不要重復(fù)聲明變量。
eslint:
no-redeclarelet name = 'John' let name = 'Jane' // ? avoid let name = 'John' name = 'Jane' // ? ok -
正則中避免使用多個(gè)空格。
eslint:
no-regex-spacesconst regexp = /test value/ // ? avoid const regexp = /test {3}value/ // ? ok const regexp = /test value/ // ? ok -
return 語句中的賦值必需有括號(hào)包裹。
eslint:
no-return-assignfunction sum (a, b) { return result = a + b // ? avoid } function sum (a, b) { return (result = a + b) // ? ok } -
避免將變量賦值給自己。
eslint:
no-self-assignname = name // ? avoid -
避免將變量與自己進(jìn)行比較操作。
esint:
no-self-compareif (score === score) {} // ? avoid -
避免使用逗號(hào)操作符。
eslint:
no-sequencesif (doSomething(), !!test) {} // ? avoid -
不要隨意更改關(guān)鍵字的值。
eslint:
no-shadow-restricted-nameslet undefined = 'value' // ? avoid -
禁止使用稀疏數(shù)組(Sparse arrays)。
eslint:
no-sparse-arrayslet fruits = ['apple',, 'orange'] // ? avoid -
不要使用制表符。
eslint:
no-tabs -
正確使用 ES6 中的字符串模板。
eslint:
no-template-curly-in-stringconst message = 'Hello ${name}' // ? avoid const message = `Hello ${name}` // ? ok -
使用
this前請確保super()已調(diào)用。eslint:
no-this-before-superclass Dog extends Animal { constructor () { this.legs = 4 // ? avoid super() } } -
用
throw拋錯(cuò)時(shí),拋出Error對象而不是字符串。eslint:
no-throw-literalthrow 'error' // ? avoid throw new Error('error') // ? ok -
行末不留空格。
eslint:
no-trailing-spaces -
不要使用
undefined來初始化變量。eslint:
no-undef-initlet name = undefined // ? avoid let name name = 'value' // ? ok -
循環(huán)語句中注意更新循環(huán)變量。
eslint:
no-unmodified-loop-conditionfor (let i = 0; i < items.length; j++) {...} // ? avoid for (let i = 0; i < items.length; i++) {...} // ? ok -
如果有更好的實(shí)現(xiàn),盡量不要使用三元表達(dá)式。
eslint:
no-unneeded-ternarylet score = val ? val : 0 // ? avoid let score = val || 0 // ? ok -
return,throw,continue和break后不要再跟代碼。eslint:
no-unreachablefunction doSomething () { return true console.log('never called') // ? avoid } -
finally代碼塊中不要再改變程序執(zhí)行流程。eslint:
no-unsafe-finallytry { // ... } catch (e) { // ... } finally { return 42 // ? avoid } -
關(guān)系運(yùn)算符的左值不要做取反操作。
eslint:
no-unsafe-negationif (!key in obj) {} // ? avoid -
避免不必要的
.call()和.apply()。eslint:
no-useless-callsum.call(null, 1, 2, 3) // ? avoid -
避免使用不必要的計(jì)算值作對象屬性。
eslint:
no-useless-computed-keyconst user = { ['name']: 'John Doe' } // ? avoid const user = { name: 'John Doe' } // ? ok -
禁止多余的構(gòu)造器。
eslint:
no-useless-constructorclass Car { constructor () { // ? avoid } } -
禁止不必要的轉(zhuǎn)義。
eslint:
no-useless-escapelet message = 'Hell\o' // ? avoid -
import, export 和解構(gòu)操作中,禁止賦值到同名變量。
eslint:
no-useless-renameimport { config as config } from './config' // ? avoid import { config } from './config' // ? ok -
屬性前面不要加空格。
eslint:
no-whitespace-before-propertyuser .name // ? avoid user.name // ? ok -
禁止使用
with。eslint:
no-withwith (val) {...} // ? avoid -
對象屬性換行時(shí)注意統(tǒng)一代碼風(fēng)格。
eslint:
object-property-newlineconst 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' } // ? ok -
代碼塊中避免多余留白。
eslint:
padded-blocksif (user) { // ? avoid const name = getName() } if (user) { const name = getName() // ? ok } -
展開運(yùn)算符與它的表達(dá)式間不要留空白。
eslint:
rest-spread-spacingfn(... args) // ? avoid fn(...args) // ? ok -
遇到分號(hào)時(shí)空格要后留前不留。
eslint:
semi-spacingfor (let i = 0 ;i < items.length ;i++) {...} // ? avoid for (let i = 0; i < items.length; i++) {...} // ? ok -
代碼塊首尾留空格。
eslint:
space-before-blocksif (admin){...} // ? avoid if (admin) {...} // ? ok -
圓括號(hào)間不留空格。
eslint:
space-in-parensgetName( name ) // ? avoid getName(name) // ? ok -
一元運(yùn)算符后面跟一個(gè)空格。
eslint:
space-unary-opstypeof!admin // ? avoid typeof !admin // ? ok -
注釋首尾留空格。
eslint:
spaced-comment//comment // ? avoid // comment // ? ok /*comment*/ // ? avoid /* comment */ // ? ok -
模板字符串中變量前后不加空格。
eslint:
template-curly-spacingconst message = `Hello, ${ name }` // ? avoid const message = `Hello, ${name}` // ? ok -
檢查
NaN的正確姿勢是使用isNaN()。eslint:
use-isnanif (price === NaN) { } // ? avoid if (isNaN(price)) { } // ? ok -
用合法的字符串跟
typeof進(jìn)行比較操作。eslint:
valid-typeoftypeof name === 'undefimed' // ? avoid typeof name === 'undefined' // ? ok -
自調(diào)用匿名函數(shù) (IIFEs) 使用括號(hào)包裹。
eslint:
wrap-iifeconst getName = function () { }() // ? avoid const getName = (function () { }()) // ? ok const getName = (function () { })() // ? ok -
yield *中的*前后都要有空格。eslint:
yield-star-spacingyield* increment() // ? avoid yield * increment() // ? ok -
請書寫優(yōu)雅的條件語句(avoid Yoda conditions)。
eslint:
yodaif (42 === age) { } // ? avoid if (age === 42) { } // ? ok -
eslint:
semiwindow.alert('hi') // ? ok window.alert('hi'); // ? avoid -
不要使用
(,[, or ``` 等作為一行的開始。在沒有分號(hào)的情況下代碼壓縮后會(huì)導(dǎo)致報(bào)錯(cuò),而堅(jiān)持這一規(guī)范則可避免出錯(cuò)。eslint:
no-unexpected-multiline// ? ok ;(function () { window.alert('ok') }()) // ? avoid (function () { window.alert('ok') }())// ? ok ;[1, 2, 3].forEach(bar) // ? avoid [1, 2, 3].forEach(bar)// ? ok ;`hello`.indexOf('o') // ? avoid `hello`.indexOf('o')備注:上面的寫法只能說聰明過頭了。
相比更加可讀易懂的代碼,那些看似投巧的寫法是不可取的。
譬如:
;[1, 2, 3].forEach(bar)建議的寫法是:
var nums = [1, 2, 3] nums.forEach(bar)
其它
控制臺(tái)輸出,用完即刪除或注釋