1.JS细则(此细则大部分参考自standard代码规范)
-
禁用var,用let和const代替。
eslint:
no-varvar a = 1 // ✗ avoid const b = 2 // ✓ ok -
使用两个空格进行缩进。
eslint:
indentfunction hello (name) { console.log('hi', name) } -
除需要转义的情况外,字符串统一使用单引号。
eslint:
quotesconsole.log('hello there') $("<div class='box'>") -
不要定义未使用的变量。
eslint:
no-unused-varsfunction myFunction () { const result = something() // ✗ avoid } -
关键字后面加空格。
eslint:
keyword-spacingif (condition) { ... } // ✓ ok if(condition) { ... } // ✗ avoid -
函数声明时括号与函数名间加空格。
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 -
字符串拼接操作 优先使用字符串模板``而不是使用
+。// ✗ avoid const name = 'Sky' const message = 'hello, ' + name + '!'// ✓ ok const name = 'Sky' const message = `hello,${name}!` -
逗号后面加空格。
eslint:
comma-spacing// ✓ ok const list = [1, 2, 3, 4] function greet (name, options) { ... }// ✗ avoid const list = [1,2,3,4] function greet (name,options) { ... } -
else 关键字要与花括号保持在同一行。
eslint:
brace-style// ✓ ok if (condition) { // ... } else { // ... }// ✗ avoid if (condition) { // ... } else { // ... } -
多行 if 语句的的括号不能省。
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参数。eslint:
handle-callback-err// ✓ ok run(function (err) { if (err) throw err window.alert('done') })// ✗ avoid run(function (err) { window.alert('done') }) -
使用浏览器全局变量时加上
window.前缀。
Exceptions are:document,consoleandnavigator.eslint:
no-undefwindow.alert('hi') // ✓ ok -
不允许有连续多行空行。
eslint:
no-multiple-empty-lines// ✓ ok const value = 'hello world' console.log(value)// ✗ avoid const value = 'hello world' console.log(value) -
对于三元运算符
?和:与他们所负责的代码处于同一行eslint:
operator-linebreak// ✓ ok const location = env.development ? 'localhost' : 'www.api.com' // ✓ ok const location = env.development ? 'localhost' : 'www.api.com' // ✗ avoid const location = env.development ? 'localhost' : 'www.api.com' -
每个 let,const 关键字单独声明一个变量。
eslint:
one-var// ✓ ok const silent = true let verbose = true // ✗ avoid const silent = true, verbose = true // ✗ avoid let silent = true, verbose = true -
条件语句中赋值语句使用括号包起来。这样使得代码更加清晰可读,而不会认为是将条件判断语句的全等号(
===)错写成了等号(=)。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 -
对于变量和函数名统一使用驼峰命名法。
eslint:
camelcasefunction my_function () { } // ✗ avoid function myFunction () { } // ✓ ok const my_var = 'hello' // ✗ avoid const myVar = 'hello' // ✓ ok -
不允许有多余的行末逗号。
eslint:
comma-dangleconst obj = { message: 'hello', // ✗ avoid } -
始终将逗号置于行末。
eslint:
comma-styleconst obj = { foo: 'foo' ,bar: 'bar' // ✗ avoid } const obj = { foo: 'foo', bar: 'bar' // ✓ ok } -
点号操作符须与属性需在同一行。
eslint:
dot-locationconsole. log('hello') // ✗ avoid console .log('hello') // ✓ ok -
文件末尾留一空行。
eslint:
eol-last -
函数调用时标识符与括号间不留间隔。
eslint:
func-call-spacingconsole.log ('hello') // ✗ avoid console.log('hello') // ✓ ok -
键值对当中冒号与值之间要留空白。
eslint:
key-spacingconst obj = { 'key' : 'value' } // ✗ avoid const obj = { 'key' :'value' } // ✗ avoid const obj = { 'key':'value' } // ✗ avoid const obj = { 'key': 'value' } // ✓ ok -
构造函数要以大写字母开头。
eslint:
new-capfunction animal () {} const dog = new animal() // ✗ avoid function Animal () {} const dog = new Animal() // ✓ ok -
无参的构造函数调用时要带上括号。
eslint:
new-parensfunction Animal () {} const dog = new Animal // ✗ avoid const dog = new Animal() // ✓ ok -
对象中定义了存值器,一定要对应的定义取值器。
eslint:
accessor-pairsconst person = { // ✗ avoid set name (value) { this._name = value } } const person = { // ✓ ok set name (value) { this._name = value }, get name () { return this._name } } -
子类的构造器中一定要调用
supereslint:
constructor-superclass Dog { constructor () { super() // ✗ avoid } } class Dog extends Mammal { constructor () { super() // ✓ ok } } -
使用数组字面量而不是构造器。
eslint:
no-array-constructorconst nums = new Array(1, 2, 3) // ✗ avoid const 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 -
避免使用常量作为条件表达式的条件(循环语句除外)。
eslint:
no-constant-conditionif (false) { // ✗ avoid // ... } if (x === 0) { // ✓ ok // ... } while (true) { // ✓ ok // ... } -
正则中不要使用控制符。
eslint:
no-control-regexconst pattern = /\x1f/ // ✗ avoid const pattern = /\x20/ // ✓ ok -
不要使用
debugger。eslint:
no-debuggerfunction sum (a, b) { debugger // ✗ avoid return a + b } -
不要对变量使用
delete操作。eslint:
no-delete-varconst name delete name // ✗ avoid -
不要定义冗余的函数参数。
eslint:
no-dupe-argsfunction sum (a, b, a) { // ✗ avoid // ... } function sum (a, b, c) { // ✓ ok // ... } -
类中不要定义冗余的属性。
eslint:
no-dupe-class-membersclass Dog { bark () {} bark () {} // ✗ avoid } -
对象字面量中不要定义重复的属性。
eslint:
no-dupe-keysconst user = { name: 'Jane Doe', name: 'John Doe' // ✗ avoid } -
switch语句中不要定义重复的case分支。eslint:
no-duplicate-caseswitch (id) { case 1: // ... case 1: // ✗ avoid } -
同一模块有多个导入时一次性写完。
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 -
不要解构空值。
eslint:
no-empty-patternconst { a: {} } = foo // ✗ avoid const { a: { b } } = foo // ✓ ok -
不要使用
eval()。eslint:
no-evaleval( "const result = user." + propName ) // ✗ avoid const result = user[propName] // ✓ ok -
catch中不要对错误重新赋值。eslint:
no-ex-assigntry { // ... } catch (e) { e = 'new value' // ✗ avoid } try { // ... } catch (e) { const newVal = 'new value' // ✓ ok } -
不要扩展原生对象。
eslint:
no-extend-nativeObject.prototype.age = 21 // ✗ avoid -
避免多余的函数上下文绑定。
eslint:
no-extra-bindconst name = function () { getName() }.bind(user) // ✗ avoid const name = function () { this.getName() }.bind(user) // ✓ ok -
避免不必要的布尔转换。
eslint:
no-extra-boolean-castconst result = true if (!!result) { // ✗ avoid // ... } const result = true if (result) { // ✓ ok // ... } -
不要使用多余的括号包裹函数。
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() } -
不要省去小数点前面的0。
eslint:
no-floating-decimalconst discount = .5 // ✗ avoid const discount = 0.5 // ✓ ok -
避免对声明过的函数重新赋值。
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 -
嵌套的代码块中禁止再定义函数。
eslint:
no-inner-declarationsif (authenticated) { function setAuthUser () {} // ✗ avoid } -
不要向
RegExp构造器传入非法的正则表达式。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-varconst score = 100 function game () { score: while (true) { // ✗ avoid score -= 10 if (score > 0) continue score break } } -
不要使用标签语句。
eslint:
no-labelslabel: // ✗ avoid while (true) { break label } -
不要书写不必要的嵌套代码块。
eslint:
no-lone-blocksfunction myFunc () { { // ✗ avoid myOtherFunc() } } function myFunc () { myOtherFunc() // ✓ ok } -
除了缩进,不要使用多个空格。
eslint:
no-multi-spacesconst id = 1234 // ✗ avoid const id = 1234 // ✓ ok -
不要使用多行字符串。
eslint:
no-multi-strconst message = 'Hello \ world' // ✗ avoid -
new创建对象实例后需要赋值给变量。eslint:
no-newnew Character() // ✗ avoid const character = new Character() // ✓ ok -
禁止使用
Function构造器。eslint:
no-new-funcconst sum = new Function('a', 'b', 'return a + b') // ✗ avoid -
禁止使用
Object构造器。eslint:
no-new-objectlet config = new Object() // ✗ avoid -
禁止使用
new require。eslint:
no-new-requireconst myModule = new require('my-module') // ✗ avoid -
禁止使用
Symbol构造器。eslint:
no-new-symbolconst foo = new Symbol('foo') // ✗ avoid -
禁止使用原始包装器。
eslint:
no-new-wrappersconst message = new String('hello') // ✗ avoid const message = 'hello' // ✓ ok -
不要将全局对象的属性作为函数调用。
eslint:
no-obj-callsconst math = Math() // ✗ avoid -
不要使用八进制字面量。
eslint:
no-octalconst num = 042 // ✗ avoid const num = '042' // ✓ ok -
字符串字面量中也不要使用八进制转义字符。
eslint:
no-octal-escapeconst copyright = 'Copyright \251' // ✗ avoid -
使用
__dirname和__filename时尽量避免使用字符串拼接。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 -
不要重复声明变量。
eslint:
no-redeclarelet name = 'John' let name = 'Jane' // ✗ avoid let name = 'John' name = 'Jane' // ✓ ok -
正则中避免使用多个空格。
eslint:
no-regex-spacesconst regexp = /test value/ // ✗ avoid const regexp = /test {3}value/ // ✓ ok const regexp = /test value/ // ✓ ok -
return 语句中的赋值必需有括号包裹。
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 -
避免将变量与自己进行比较操作。
esint:
no-self-compareif (score === score) {} // ✗ avoid -
避免使用逗号操作符。
eslint:
no-sequencesif (doSomething(), !!test) {} // ✗ avoid -
不要随意更改关键字的值。
eslint:
no-shadow-restricted-nameslet undefined = 'value' // ✗ avoid -
禁止使用稀疏数组(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()已调用。eslint:
no-this-before-superclass Dog extends Animal { constructor () { this.legs = 4 // ✗ avoid super() } } -
用
throw抛错时,抛出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 -
如果有更好的实现,尽量不要使用三元表达式。
eslint:
no-unneeded-ternarylet score = val ? val : 0 // ✗ avoid let score = val || 0 // ✓ ok const success = true success ? doSomething() : '' // ✗ avoid success && doSomething() // ✓ ok -
return,throw,continue和break后不要再跟代码。eslint:
no-unreachablefunction doSomething () { return true console.log('never called') // ✗ avoid } -
finally代码块中不要再改变程序执行流程。eslint:
no-unsafe-finallytry { // ... } catch (e) { // ... } finally { return 42 // ✗ avoid } -
关系运算符的左值不要做取反操作。
eslint:
no-unsafe-negationif (!key in obj) {} // ✗ avoid -
避免不必要的
.call()和.apply()。eslint:
no-useless-callsum.call(null, 1, 2, 3) // ✗ avoid -
避免使用不必要的计算值作对象属性。
eslint:
no-useless-computed-keyconst user = { ['name']: 'John Doe' } // ✗ avoid const user = { name: 'John Doe' } // ✓ ok -
禁止多余的构造器。
eslint:
no-useless-constructorclass Car { constructor () { // ✗ avoid } } -
禁止不必要的转义。
eslint:
no-useless-escapelet message = 'Hell\o' // ✗ avoid -
import, export 和解构操作中,禁止赋值到同名变量。
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 -
对象属性换行时注意统一代码风格。
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 } -
展开运算符与它的表达式间不要留空白。
eslint:
rest-spread-spacingfn(... args) // ✗ avoid fn(...args) // ✓ ok -
遇到分号时空格要后留前不留。
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 -
圆括号间不留空格。
eslint:
space-in-parensgetName( name ) // ✗ avoid getName(name) // ✓ ok -
一元运算符后面跟一个空格。
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进行比较操作。eslint:
valid-typeoftypeof name === 'undefimed' // ✗ avoid typeof name === 'undefined' // ✓ ok -
自调用匿名函数 (IIFEs) 使用括号包裹。
eslint:
wrap-iifeconst getName = function () { }() // ✗ avoid const getName = (function () { }()) // ✓ ok const getName = (function () { })() // ✓ ok -
yield *中的*前后都要有空格。eslint:
yield-star-spacingyield* increment() // ✗ avoid yield * increment() // ✓ ok -
请书写优雅的条件语句(avoid Yoda conditions)。
eslint:
yodaif (42 === age) { } // ✗ avoid if (age === 42) { } // ✓ ok -
不要使用分号。
eslint:
semiwindow.alert('hi') // ✓ ok window.alert('hi'); // ✗ avoid -
不要使用
(,[, or`等作为一行的开始。在没有分号的情况下代码压缩后会导致报错,而坚持这一规范则可避免出错。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)建议的写法是:
const nums = [1, 2, 3] nums.forEach(bar)
2.HTML细则
-
属性值统一使用双引号包裹。
<input type='text'> // ✗ avoid <input type="text"> // ✓ ok -
HTML元素及其单单词属性统一使用小写字母。
<INPUT TYPE="TEXT"> // ✗ avoid <input type="text"> // ✓ ok -
id和name使用驼峰命名。
<input id="test_id" name="test_name"> // ✗ avoid <input id="testId" name="testName"> // ✓ ok <input id="test" name="test"> // ✓ ok -
自定义组件名单词之间的分隔符使用
-。Custom Elements 标准对自定义元素的名字做了限制:“自定义元素的名字必须包含一个破折号(-)所以<x-tags>、<my-element>和<my-awesome-app>都是正确的名字,而<tabs>和<foo_bar>是不正确的。这样的限制使得 HTML 解析器可以分辨那些是标准元素,哪些是自定义元素。”<elInput></elInput> // ✗ avoid <el_input></el_input> // ✗ avoid <el-input></el-input> // ✓ ok -
HTML或JSP页面,样式表在
<head>标签的底部进行引入,<script>标签在<body>标签的底部引入,引入顺序为框架公用=>项目公用=>组件私用。 禁止在页面中的style标签中写样式。 例外:公用的组件中推荐在style中写组件私有样式,而非使用公用的样式表<head> <!--框架公用--> <link rel="stylesheet" href="./static/css/weui.min.css"> <!--项目公用--> <link rel="stylesheet" href="./static/css/wechat.css"> <!--组件私用--> <link rel="stylesheet" href="./static/css/index.css"> </head> <body> ... <!--框架公用--> <script type="text/javascript" src="../assets/js/vue.min.js"></script> <!--项目公用--> <script type="text/javascript" src="../assets/js/zepto.min.js"></script> <!--组件私用--> <script type="text/javascript" src="../assets/js/index.js"></script> </body> -
按需引入资源文件,非必要情况下不做全局引入
-
数据不需要双向绑定的时候,一律使用单向绑定
3.CSS细则
-
样式命名统一用全小写英文单词,单词之间使用
-分隔。// ✓ ok .color-red { ... } // ✗ avoid .color_red { ... } // ✗ avoid .colorRed { ... } -
禁止使用id、name等优先级高的选择器去控制样式
// ✗ avoid #app { ... }// ✗ avoid input[name="appName"] { ... } -
尽量避免使用
!important关键字,否则将很难动态修改该样式。// ✗ avoid .color-red { color: red !important; }
3.1常用的CSS命名规则
- 头:header
- 内容:content
- 尾:footer
- 导航:nav
- 侧栏:sidebar
- 栏目:column
- 页面外围控制整体佈局宽度:wrapper
- 左右中:left right center
- 登录条:loginbar
- 标志:logo
- 广告:banner
- 页面主体:main
- 热点:hot
- 新闻:news
- 下载:download
- 子导航:subnav
- 菜单:menu
- 子菜单:submenu
- 搜索:search
- 友情链接:friend-link
- 页脚:footer
- 版权:copyright
- 滚动:scroll
- 内容:content
- 标签:tags
- 文章列表:list
- 提示信息:msg
- 小技巧:tips
- 栏目标题:title
- 加入:join-us
- 指南:guide
- 服务:service
- 注册:regsiter
- 状态:status
- 投票:vote
- 合作伙伴:partner
- 友情链接:link