参考
airbnb:https://github.com/airbnb/javascript
standard:https://standardjs.com/rules.html
Standard
禁止未引用变量
function myFunction () {var result = something() // ✗ avoid}
异常抛出
// ✓ okrun(function (err) {if (err) throw errwindow.alert('done')})// ✗ avoidrun(function (err) {window.alert('done')})
三元表达式书写
// ✓ okvar location = env.development ? 'localhost' : 'www.api.com'// ✓ okvar location = env.development? 'localhost': 'www.api.com'// ✗ avoidvar location = env.development ?'localhost' :'www.api.com'
new构造器必须大写
function animal () {}var dog = new animal() // ✗ avoidfunction Animal () {}var dog = new Animal() // ✓ ok
对象设置了setter以后,必须设置getter
var person = {set name (value) { // ✗ avoidthis._name = value}}var person = {set name (value) {this._name = value},get name () { // ✓ okreturn this._name}}
禁止array构造器
var nums = new Array(1, 2, 3) // ✗ avoidvar nums = [1, 2, 3] // ✓ ok
禁止使用arguments.callee 和 arguments.caller
function foo (n) {if (n <= 0) returnarguments.callee(n - 1) // ✗ avoid}function foo (n) {if (n <= 0) returnfoo(n - 1) // ✓ ok}
删除debugger
function sum (a, b) {debugger // ✗ avoidreturn a + b}
禁止使用delete操作符
var namedelete name // ✗ avoid
合并导入
import { myFunc1 } from 'module'import { myFunc2 } from 'module' // ✗ avoidimport { myFunc1, myFunc2 } from 'module' // ✓ ok
禁止eval
eval( "var result = user." + propName ) // ✗ avoidvar result = user[propName] // ✓ ok
异常捕获禁止重新赋值
try {// ...} catch (e) {e = 'new value' // ✗ avoid}try {// ...} catch (e) {const newVal = 'new value' // ✓ ok
避免不必要的布尔值判断
const result = trueif (!!result) { // ✗ avoid// ...}const result = trueif (result) { // ✓ ok// ...}
switch要写break
switch (filter) {case 1:doSomething() // ✗ avoidcase 2:doSomethingElse()}switch (filter) {case 1:doSomething()break // ✓ okcase 2:doSomethingElse()}switch (filter) {case 1:doSomething()// fallthrough // ✓ okcase 2:doSomethingElse()}
禁止在嵌套块中声明函数
if (authenticated) {function setAuthUser () {} // ✗ avoid}
new构造函数需要赋值
new Character() // ✗ avoidconst character = new Character() // ✓ ok
路径拼接
const pathToFile = __dirname + '/app.js' // ✗ avoidconst pathToFile = path.join(__dirname, 'app.js') // ✓ ok
赋值返回必须写括号
function sum (a, b) {return result = a + b // ✗ avoid}function sum (a, b) {return (result = a + b) // ✓ ok}
异常抛出
throw 'error' // ✗ avoidthrow new Error('error') // ✓ ok
使用或代替三元
let score = val ? val : 0 // ✗ avoidlet score = val || 0 // ✓ ok
移除不必要的构造器
class Car {constructor () { // ✗ avoid}}
