JavaScript Standard Style
npm install @woolson/standard
这是 JavaScript standard 代码规范的全文。
*使用Tab进行缩进。
eslint: indent
``js`
function hello (name) {
console.log('hi', name)
}
* 除需要转义的情况外,字符串统一使用单引号。
eslint: quotes
` * 不要定义未使用的变量。 * 关键字后面加空格。 * 函数声明时括号与函数名间加空格。 run(function () { ... }) // ✓ ok * 始终使用 * 字符串拼接操作符 (Infix operators) 之间要留空格。 * 逗号后面加空格。 * else 关键字要与花括号保持在同一行。 * 多行 if 语句的的括号不能省。 * 不要丢掉异常处理中 * 使用浏览器全局变量时加上 * 不允许有连续多行空行。 * 对于三元运算符 // ✓ ok // ✗ avoid * 每个 var 关键字单独声明一个变量。 // ✗ avoid // ✗ avoid * 条件语句中赋值语句使用括号包起来。这样使得代码更加清晰可读,而不会认为是将条件判断语句的全等号( // ✗ avoid * 单行代码块两边加空格。 * 对于变量和函数名统一使用驼峰命名法。 var my_var = 'hello' // ✗ avoid * 不允许有多余的行末逗号。 * 始终将逗号置于行末。 var obj = { * 点号操作符须与属性需在同一行。 console * 文件末尾留一空行。 * 函数调用时标识符与括号间不留间隔。 * 键值对当中冒号与值之间要留空白。 * 构造函数要以大写字母开头。 function Animal () {} * 无参的构造函数调用时要带上括号。 * 对象中定义了存值器,一定要对应的定义取值器。 var person = { * 子类的构造器中一定要调用 class Dog extends Mammal { * 使用数组字面量而不是构造器。 * 避免使用 arguments.callee(n - 1) // ✗ avoid function foo (n) { foo(n - 1) * 避免对类名重新赋值。 * 避免修改使用 * 避免使用常量作为条件表达式的条件(循环语句除外)。 if (x === 0) { // ✓ ok while (true) { // ✓ ok * 正则中不要使用控制符。 * 不要使用 * 不要对变量使用 * 不要定义冗余的函数参数。 function sum (a, b, c) { // ✓ ok * 类中不要定义冗余的属性。 * 对象字面量中不要定义重复的属性。 * * 同一模块有多个导入时一次性写完。 import { myFunc1, myFunc2 } from 'module' // ✓ ok * 正则中不要使用空字符。 * 不要解构空值。 * 不要使用 * try { * 不要扩展原生对象。 * 避免多余的函数上下文绑定。 const name = function () { * 避免不必要的布尔转换。 const result = true * 不要使用多余的括号包裹函数。 * switch (filter) { switch (filter) { * 不要省去小数点前面的0。 * 避免对声明过的函数重新赋值。 * 不要对全局只读对象重新赋值。 * 注意隐式的 * 嵌套的代码块中禁止再定义函数。 * 不要向 * 不要使用非法的空白符。 * 禁止使用 * 外部变量不要与对象属性重名。 * 不要使用标签语句。 * 不要书写不必要的嵌套代码块。 function myFunc () { * 不要混合使用空格与制表符作为缩进。 * 除了缩进,不要使用多个空格。 * 不要使用多行字符串。 * * 禁止使用 * 禁止使用 * 禁止使用 * 禁止使用 * 禁止使用原始包装器。 * 不要将全局对象的属性作为函数调用。 * 不要使用八进制字面量。 * 字符串字面量中也不要使用八进制转义字符。 * 使用 * 使用 * 不要重复声明变量。 let name = 'John' * 正则中避免使用多个空格。 const regexp = /test {3}value/ // ✓ ok * return 语句中的赋值必需有括号包裹。 function sum (a, b) { * 避免将变量赋值给自己。 * 避免将变量与自己进行比较操作。 * 避免使用逗号操作符。 * 不要随意更改关键字的值。 * 禁止使用稀疏数组(Sparse arrays)。 * 不要使用制表符。 * 正确使用 ES6 中的字符串模板。 * 使用 * 用 * 行末不留空格。 * 不要使用 let name * 循环语句中注意更新循环变量。 * 如果有更好的实现,尽量不要使用三元表达式。 * * * 关系运算符的左值不要做取反操作。 * 避免不必要的 * 避免使用不必要的计算值作对象属性。 * 禁止多余的构造器。 * 禁止不必要的转义。 * import, export 和解构操作中,禁止赋值到同名变量。 * 属性前面不要加空格。 * 禁止使用 * 对象属性换行时注意统一代码风格。 const user = { name: 'Jane Doe', age: 30, username: 'jdoe86' } // ✓ ok const user = { * 代码块中避免多余留白。 } if (user) { * 展开运算符与它的表达式间不要留空白。 * 遇到分号时空格要后留前不留。 * 代码块首尾留空格。 * 圆括号间不留空格。 * 一元运算符后面跟一个空格。 * 注释首尾留空格。 /comment/ // ✗ avoid * 模板字符串中变量前后不加空格。 * 检查 * 用合法的字符串跟 * 自调用匿名函数 (IIFEs) 使用括号包裹。 const getName = (function () { }()) // ✓ ok * 请书写优雅的条件语句(avoid Yoda conditions)。 * 不要使用 eslint: [ ` // ✗ avoid ` // ✗ avoid ` // ✗ avoid 备注:上面的写法只能说聪明过头了。 相比更加可读易懂的代码,那些看似投巧的写法是不可取的。 譬如: ` 建议的写法是: ` - [An Open Letter to JavaScript Leaders Regarding Semicolons][1] ##### 一个值得观看的视频: - [JavaScript 中的分号多余吗?- YouTube][3] 当前主流的代码压缩方案都是基于词法(AST-based)进行的,所以在处理无分号的代码时完全没有压力(何况 JavaScript 中分号本来就不是强制的)。 ##### 一段摘抄自 ["An Open Letter to JavaScript Leaders Regarding Semicolons"][1] 这篇文章的内容: > [自动化插入分号的做法]是安全可依赖的,而且其产出的代码能够在所有浏览器里很好地运行。 Closure compiler, yuicompressor, packer 还有 jsmin 都能正确地对这样的代码进行压缩处理。并没有任何性能相关的问题。 [1]: http://blog.izs.me/post/2353458699/an-open-letter-to-javascript-leaders-regardingjs
console.log('hello there')
$("")
`no-unused-vars`js`
function myFunction () {
var result = something() // ✗ avoid
}
keyword-spacing`js`
if (condition) { ... } // ✓ ok
if(condition) { ... } // ✗ avoid
space-before-function-paren`js`
function name (arg) { ... } // ✓ ok
function name(arg) { ... } // ✗ avoid
run(function() { ... }) // ✗ avoid
=== 替代 ==。obj == null
例外: 可以用来检查 null || undefined。eqeqeq`js`
if (name === 'John') // ✓ ok
if (name == 'John') // ✗ avoid
`js`
if (name !== 'John') // ✓ ok
if (name != 'John') // ✗ avoid
space-infix-ops`js`
// ✓ ok
var x = 2
var message = 'hello, ' + name + '!'
`js`
// ✗ avoid
var x=2
var message = 'hello, '+name+'!'
comma-spacing`js`
// ✓ ok
var list = [1, 2, 3, 4]
function greet (name, options) { ... }
`js`
// ✗ avoid
var list = [1,2,3,4]
function greet (name,options) { ... }
brace-style`js`
// ✓ ok
if (condition) {
// ...
} else {
// ...
}
`js`
// ✗ avoid
if (condition) {
// ...
}
else {
// ...
}
curly`js`
// ✓ ok
if (options.quiet !== true) console.log('done')
`js`
// ✓ ok
if (options.quiet !== true) {
console.log('done')
}
`js`
// ✗ avoid
if (options.quiet !== true)
console.log('done')
err参数。handle-callback-err`
js`
// ✓ ok
run(function (err) {
if (err) throw err
window.alert('done')
})
`js`
// ✗ avoid
run(function (err) {
window.alert('done')
})
window. 前缀。document
Exceptions are: , console and navigator.no-undef`js`
window.alert('hi') // ✓ ok
no-multiple-empty-lines`js`
// ✓ ok
var value = 'hello world'
console.log(value)
`js`
// ✗ avoid
var value = 'hello world'
console.log(value)
? 和 : 与他们所负责的代码处于同一行operator-linebreak`js`
// ✓ ok
var location = env.development ? 'localhost' : 'www.api.com'
var location = env.development
? 'localhost'
: 'www.api.com'
var location = env.development ?
'localhost' :
'www.api.com'
one-var`js`
// ✓ ok
var silent = true
var verbose = true
var silent = true, verbose = true
var silent = true,
verbose = true
===)错写成了等号(=)。no-cond-assign`js`
// ✓ ok
while ((m = text.match(expr))) {
// ...
}
while (m = text.match(expr)) {
// ...
}
block-spacing`js`
function foo () {return true} // ✗ avoid
function foo () { return true } // ✓ ok
camelcase`js`
function my_function () { } // ✗ avoid
function myFunction () { } // ✓ ok
var myVar = 'hello' // ✓ ok
comma-dangle`js`
var obj = {
message: 'hello', // ✗ avoid
}
comma-style`js`
var obj = {
foo: 'foo'
,bar: 'bar' // ✗ avoid
}
foo: 'foo',
bar: 'bar' // ✓ ok
}
dot-location`js`
console.
log('hello') // ✗ avoid
.log('hello') // ✓ ok
eol-lastfunc-call-spacing`js`
console.log ('hello') // ✗ avoid
console.log('hello') // ✓ ok
key-spacing`js`
var obj = { 'key' : 'value' } // ✗ avoid
var obj = { 'key' :'value' } // ✗ avoid
var obj = { 'key':'value' } // ✗ avoid
var obj = { 'key': 'value' } // ✓ ok
new-cap`js`
function animal () {}
var dog = new animal() // ✗ avoid
var dog = new Animal() // ✓ ok
new-parens`js`
function Animal () {}
var dog = new Animal // ✗ avoid
var dog = new Animal() // ✓ ok
accessor-pairs`js`
var person = {
set name (value) { // ✗ avoid
this.name = value
}
}
set name (value) {
this.name = value
},
get name () { // ✓ ok
return this.name
}
}
superconstructor-super`js`
class Dog {
constructor () {
super() // ✗ avoid
}
}
constructor () {
super() // ✓ ok
}
}
no-array-constructor`js`
var nums = new Array(1, 2, 3) // ✗ avoid
var nums = [1, 2, 3] // ✓ ok
arguments.callee 和 arguments.caller。no-caller`js`
function foo (n) {
if (n <= 0) return
}
if (n <= 0) return
}
no-class-assign`js`
class Dog {}
Dog = 'Fido' // ✗ avoid
const 声明的变量。no-const-assign`js`
const score = 100
score = 125 // ✗ avoid
no-constant-condition`js`
if (false) { // ✗ avoid
// ...
}
// ...
}
// ...
}
no-control-regex`js`
var pattern = /\x1f/ // ✗ avoid
var pattern = /\x20/ // ✓ ok
debugger。no-debugger`js`
function sum (a, b) {
debugger // ✗ avoid
return a + b
}
delete 操作。no-delete-var`js`
var name
delete name // ✗ avoid
no-dupe-args`js`
function sum (a, b, a) { // ✗ avoid
// ...
}
// ...
}
no-dupe-class-members`js`
class Dog {
bark () {}
bark () {} // ✗ avoid
}
no-dupe-keys`js`
var user = {
name: 'Jane Doe',
name: 'John Doe' // ✗ avoid
}
switch 语句中不要定义重复的 case 分支。no-duplicate-case`js`
switch (id) {
case 1:
// ...
case 1: // ✗ avoid
}
no-duplicate-imports`js`
import { myFunc1 } from 'module'
import { myFunc2 } from 'module' // ✗ avoid
no-empty-character-class`js`
const myRegex = /^abc[]/ // ✗ avoid
const myRegex = /^abc[a-z]/ // ✓ ok
no-empty-pattern`js`
const { a: {} } = foo // ✗ avoid
const { a: { b } } = foo // ✓ ok
eval()。no-eval`js`
eval( "var result = user." + propName ) // ✗ avoid
var result = user[propName] // ✓ ok
catch 中不要对错误重新赋值。no-ex-assign`js`
try {
// ...
} catch (e) {
e = 'new value' // ✗ avoid
}
// ...
} catch (e) {
const newVal = 'new value' // ✓ ok
}
no-extend-native`js`
Object.prototype.age = 21 // ✗ avoid
no-extra-bind`js`
const name = function () {
getName()
}.bind(user) // ✗ avoid
this.getName()
}.bind(user) // ✓ ok
no-extra-boolean-cast`js`
const result = true
if (!!result) { // ✗ avoid
// ...
}
if (result) { // ✓ ok
// ...
}
no-extra-parens`js`
const myFunc = (function () { }) // ✗ avoid
const myFunc = function () { } // ✓ ok
switch 一定要使用 break 来将条件分支正常中断。no-fallthrough`js`
switch (filter) {
case 1:
doSomething() // ✗ avoid
case 2:
doSomethingElse()
}
case 1:
doSomething()
break // ✓ ok
case 2:
doSomethingElse()
}
case 1:
doSomething()
// fallthrough // ✓ ok
case 2:
doSomethingElse()
}
no-floating-decimal`js`
const discount = .5 // ✗ avoid
const discount = 0.5 // ✓ ok
no-func-assign`js`
function myFunc () { }
myFunc = myOtherFunc // ✗ avoid
no-global-assign`js`
window = {} // ✗ avoid
eval()。no-implied-eval`js`
setTimeout("alert('Hello world')") // ✗ avoid
setTimeout(function () { alert('Hello world') }) // ✓ ok
no-inner-declarations`js`
if (authenticated) {
function setAuthUser () {} // ✗ avoid
}
RegExp 构造器传入非法的正则表达式。no-invalid-regexp`js`
RegExp('[a-z') // ✗ avoid
RegExp('[a-z]') // ✓ ok
no-irregular-whitespace`js`
function myFunc () /
__iterator__。no-iterator`js`
Foo.prototype.__iterator__ = function () {} // ✗ avoid
no-label-var`js`
var score = 100
function game () {
score: 50 // ✗ avoid
}
no-labels`js`
label:
while (true) {
break label // ✗ avoid
}
no-lone-blocks`js`
function myFunc () {
{ // ✗ avoid
myOtherFunc()
}
}
myOtherFunc() // ✓ ok
}
no-mixed-spaces-and-tabsno-multi-spaces`js`
const id = 1234 // ✗ avoid
const id = 1234 // ✓ ok
no-multi-str`js`
const message = 'Hello \
world' // ✗ avoid
new 创建对象实例后需要赋值给变量。no-new`js`
new Character() // ✗ avoid
const character = new Character() // ✓ ok
Function 构造器。no-new-func`js`
var sum = new Function('a', 'b', 'return a + b') // ✗ avoid
Object 构造器。no-new-object`js`
let config = new Object() // ✗ avoid
new require。no-new-require`js`
const myModule = new require('my-module') // ✗ avoid
Symbol 构造器。no-new-symbol`js`
const foo = new Symbol('foo') // ✗ avoid
no-new-wrappers`js`
const message = new String('hello') // ✗ avoid
no-obj-calls`js`
const math = Math() // ✗ avoid
no-octal`js`
const num = 042 // ✗ avoid
const num = '042' // ✓ ok
no-octal-escape`js`
const copyright = 'Copyright \251' // ✗ avoid
__dirname 和 __filename 时尽量避免使用字符串拼接。no-path-concat`js`
const pathToFile = __dirname + '/app.js' // ✗ avoid
const pathToFile = path.join(__dirname, 'app.js') // ✓ ok
getPrototypeOf 来替代 __proto__。no-proto`js`
const foo = obj.__proto__ // ✗ avoid
const foo = Object.getPrototypeOf(obj) // ✓ ok
no-redeclare`js`
let name = 'John'
let name = 'Jane' // ✗ avoid
name = 'Jane' // ✓ ok
no-regex-spaces`js`
const regexp = /test value/ // ✗ avoid
const regexp = /test value/ // ✓ ok
no-return-assign`js`
function sum (a, b) {
return result = a + b // ✗ avoid
}
return (result = a + b) // ✓ ok
}
no-self-assign`js`
name = name // ✗ avoid
no-self-compare`js`
if (score === score) {} // ✗ avoid
no-sequences`js`
if (doSomething(), !!test) {} // ✗ avoid
no-shadow-restricted-names`js`
let undefined = 'value' // ✗ avoid
no-sparse-arrays`js`
let fruits = ['apple',, 'orange'] // ✗ avoid
no-tabsno-template-curly-in-string`jsHello ${name}
const message = 'Hello ${name}' // ✗ avoid
const message = // ✓ ok`
this 前请确保 super() 已调用。no-this-before-super`js`
class Dog extends Animal {
constructor () {
this.legs = 4 // ✗ avoid
super()
}
}
throw 抛错时,抛出 Error 对象而不是字符串。no-throw-literal`js`
throw 'error' // ✗ avoid
throw new Error('error') // ✓ ok
no-trailing-spacesundefined 来初始化变量。no-undef-init`js`
let name = undefined // ✗ avoid
name = 'value' // ✓ ok
no-unmodified-loop-condition`js`
for (let i = 0; i < items.length; j++) {...} // ✗ avoid
for (let i = 0; i < items.length; i++) {...} // ✓ ok
no-unneeded-ternary`js`
let score = val ? val : 0 // ✗ avoid
let score = val || 0 // ✓ ok
return,throw,continue 和 break 后不要再跟代码。no-unreachable`js`
function doSomething () {
return true
console.log('never called') // ✗ avoid
}
finally 代码块中不要再改变程序执行流程。no-unsafe-finally`js`
try {
// ...
} catch (e) {
// ...
} finally {
return 42 // ✗ avoid
}
no-unsafe-negation`js`
if (!key in obj) {} // ✗ avoid
.call() 和 .apply()。no-useless-call`js`
sum.call(null, 1, 2, 3) // ✗ avoid
no-useless-computed-key`js`
const user = { ['name']: 'John Doe' } // ✗ avoid
const user = { name: 'John Doe' } // ✓ ok
no-useless-constructor`js`
class Car {
constructor () { // ✗ avoid
}
}
no-useless-escape`js`
let message = 'Hell\o' // ✗ avoid
no-useless-rename`js`
import { config as config } from './config' // ✗ avoid
import { config } from './config' // ✓ ok
no-whitespace-before-property`js`
user .name // ✗ avoid
user.name // ✓ ok
with。no-with`js`
with (val) {...} // ✗ avoid
object-property-newline`js`
const user = {
name: 'Jane Doe', age: 30,
username: 'jdoe86' // ✗ avoid
}
name: 'Jane Doe',
age: 30,
username: 'jdoe86'
} // ✓ ok
padded-blocks`js`
if (user) {
// ✗ avoid
const name = getName()
const name = getName() // ✓ ok
}
rest-spread-spacing`js`
fn(... args) // ✗ avoid
fn(...args) // ✓ ok
semi-spacing`js`
for (let i = 0 ;i < items.length ;i++) {...} // ✗ avoid
for (let i = 0; i < items.length; i++) {...} // ✓ ok
space-before-blocks`js`
if (admin){...} // ✗ avoid
if (admin) {...} // ✓ ok
space-in-parens`js`
getName( name ) // ✗ avoid
getName(name) // ✓ ok
space-unary-ops`js`
typeof!admin // ✗ avoid
typeof !admin // ✓ ok
spaced-comment`js`
//comment // ✗ avoid
// comment // ✓ ok
/ comment / // ✓ ok
template-curly-spacing`jsHello, ${ name }
const message = // ✗ avoidHello, ${name}
const message = // ✓ ok`
NaN 的正确姿势是使用 isNaN()。use-isnan`js`
if (price === NaN) { } // ✗ avoid
if (isNaN(price)) { } // ✓ ok
typeof 进行比较操作。valid-typeof`js`
typeof name === 'undefimed' // ✗ avoid
typeof name === 'undefined' // ✓ ok
wrap-iife`js`
const getName = function () { }() // ✗ avoid
const getName = (function () { })() // ✓ ok
yield 中的 * 前后都要有空格。yield-star-spacing`js`
yield* increment() // ✗ avoid
yield * increment() // ✓ ok
yoda`js`
if (42 === age) { } // ✗ avoid
if (age === 42) { } // ✓ ok
semi关于分号
`js`
window.alert('hi') // ✓ ok
window.alert('hi'); // ✗ avoid
(, , or ` 等作为一行的开始。在没有分号的情况下代码压缩后会导致报错,而坚持这一规范则可避免出错。no-unexpected-multilinejs
// ✓ ok
;(function () {
window.alert('ok')
}())
(function () {
window.alert('ok')
}())
`js
// ✓ ok
;[1, 2, 3].forEach(bar)
[1, 2, 3].forEach(bar)
`jshello
// ✓ ok
;.indexOf('o')
hello.indexOf('o')`
js`
;[1, 2, 3].forEach(bar)
js`
var nums = [1, 2, 3]
nums.forEach(bar)
拓展阅读
- [JavaScript Semicolon Insertion – Everything you need to know][2]
>
> 不得不说,Javascript 社区里的大牛们一直是错误的,并不能教给你最佳实践。真是让人忧伤啊。 我建议先弄清楚 JS 是怎样断句的(还有就是哪些地方看起来断了其实并没有),明白了这个后就可以随心写出漂亮的代码了。
>
> 一般来说, \n 表示语句结束,除非:.
> 1. 该语句有未闭合的括号, 数组字面量, 对象字面量 或者其他不能正常结束一条语句的情况(譬如,以 或 , 结尾)--
> 2. 该语句是 或者 ++ (它会将后面的内容进行自增或减)for()
> 3. 该语句是 ,while(),do,if() 或者 else 并且没有 {[
> 4. 下一行以 ,(,+,*,/,-,,,. 或者其他只会单独出现在两块内容间的二元操作符。var
>
> 第一条很容易理解。即使在 JSLint 中,也允许 JSON,构造器的括号中,以及使用 配合 , 结尾来声明多个变量等这些情中包含 \n。i\n++\nj
>
> 第二条有点奇葩。 我还想不出谁会(除了这里用作讨论外)写出 这样的代码来,不过,顺便说一下,这种写法最后解析的结果是 i; ++j,而不是 i++; j。if (x)\ny()
>
> 第三条也容易理解。 等价于 if (x) { y() }。解释器会向下寻找到代码块或一条语句为止。;
>
> 是条合法的 JavaScript 语句。所以 if(x); 等价于 if(x){},表示 “如果 x 为真,什么也不做。” 这种写法在循环里面可以看到,就是当条件判断与条件更新是同一个方法的时候。 不常见,但也不至于没听说过吧。`
>
> 第四条就是常见的 “看,说过要加分号!” 的情形。但这些情况可以通过在语句前面加上分号来解决,如果你确定该语句跟前面的没关系的话。举个例子,假如你想这样:
>
> js`
> foo();
> [1,2,3].forEach(bar);
> `
>
> 那么完全可以这样来写:
>
> js`
> foo()
> ;[1,2,3].forEach(bar)
> (
>
> 后者的好处是分号比较瞩目,一旦习惯后便再也不会看到以 和 [` 开头又不带分号的语句了。
[2]: http://inimino.org/~inimino/blog/javascript_semicolons
[3]: https://www.youtube.com/watch?v=gsfbh17Ax9I