一、部署 eslint 规范 JavaScript
1.1 原理
husky + lint-staged + prettier + eslint + commitlint
- husky: 阻止不规范的
git commit,git push。 - lint-staged: 只检测待提交区的代码。
1.2 安装依赖
npm i husky lint-staged prettier prettier-eslint-cli eslint babel-eslint eslint-config-standard eslint-plugin-standard eslint-plugin-import eslint-plugin-node eslint-plugin-promise eslint-plugin-standard @commitlint/{config-conventional,cli} --save-dev
Vue 项目需要额外安装:
npm i eslint-plugin-vue --save-dev
1.3 配置 .prettierrc
{
"semi": true
}
配置 .prettierignore 忽略必要的文件:
node_modules/
dist/
1.4 配置 .eslintrc.js
module.exports = {
root: true, // 指定跟路径
parserOptions: {
sourceType: 'module', // ECMAScript模块
ecmaVersion: 8, // js版本 https://eslint.org/docs/user-guide/configuring/language-options#specifying-parser-options
parser: 'babel-eslint', // 解析器
ecmaFeatures: {
experimentalObjectRestSpread: true
}
},
env: {
browser: true, // 浏览器启用
node: true, // node启用
es6: true // es6启用
},
extends: [
'standard' // js标准规则
// https://standardjs.com/rules-zhcn.html#javascript-standard-style
],
// add your custom rules here
rules: {
indent: ['error', 2], // 缩进宽度2个空格
// 根据ECMAScript 5(和ECMAScript 3!)规范,对象文字中的尾随逗号是有效的。但是,IE8(当不在IE8文档模式下)遇到尾随逗号时会引发错误。
'comma-dangle': 'off', // 允许行末逗号
'no-constant-condition': 'off', // 允许常量作为表达式条件
'no-delete-var': 'off', // 允许使用delete
'no-extend-native': 'off', // 允许扩展原生对象
'no-floating-decimal': 'off', // 允许省去小数点前的0
'no-multi-str': 'off', // 允许多行字符串
// allow async-await
'generator-star-spacing': 'off', // 关闭
camelcase: 'off', // 允许非驼峰
semi: ['error', 'always'], // 使用分号
// no-unused-vars 老版本配置,现在会报错 'no-unused-vars': ['warn', 'always'], // 未使用变量
'no-unused-vars': ['warn', { vars: 'all', args: 'after-used', ignoreRestSiblings: false }], // 未使用变量
// 最大长度 120
'max-len': [
'warn',
{
code: 120,
ignoreComments: true,
ignoreStrings: true,
ignoreTemplateLiterals: true,
ignoreUrls: true
}
],
// 最大行数 500
'max-lines': [
'warn',
{
max: 500,
skipBlankLines: true,
skipComments: true
}
],
// 要求使用 let 或 const 而不是 var
'no-var': ['error'],
// allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off'
}
};
Vue 项目配置:
module.exports = {
root: true, // 指定跟路径
parserOptions: {
sourceType: 'module', // ECMAScript模块
ecmaVersion: 6, // js版本
parser: 'babel-eslint' // 解析器
},
env: {
browser: true // 浏览器启用
},
extends: [
// https://github.com/vuejs/eslint-plugin-vue#priority-a-essential-error-prevention
// consider switching to `plugin:vue/strongly-recommended` or `plugin:vue/recommended` for stricter rules.
'plugin:vue/essential', // vue基本规则
// https://github.com/standard/standard/blob/master/docs/RULES-en.md
'standard' // js标准规则
// https://standardjs.com/rules-zhcn.html#javascript-standard-style
],
// required to lint *.vue files
plugins: [
'vue' // 支持vue文件
],
// add your custom rules here
rules: {
'indent': ['error', 4], // 缩进宽度4个空格
'comma-dangle': 'off', // 允许行末逗号
'no-constant-condition': 'off', // 允许常量作为表达式条件
'no-delete-var': 'off', // 允许使用delete
'no-extend-native': 'off', // 允许扩展原生对象
'no-floating-decimal': 'off', // 允许省去小数点前的0
'no-multi-str': 'off', // 允许多行字符串
'semi': 'off', // 允许使用分号
// allow async-await
'generator-star-spacing': 'off', // 关闭
// 最大长度 120
'max-len': [
'warn',
{
'code': 120,
'ignoreComments': true,
'ignoreStrings': true,
'ignoreTemplateLiterals': true,
'ignoreUrls': true
}
],
// 最大行数 500
'max-lines': [
'warn',
{
'max': 500,
'skipBlankLines': true,
'skipComments': true
}
],
// 要求使用 let 或 const 而不是 var
'no-var': [
'error'
],
// allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off'
}
}
另外可以配置 .eslintignore 忽略指定规则的文件:
node_modules/
dist/
lib/
1.5 配置 .lintstagedrc
{
"*.js": [
"prettier-eslint --write",
"eslint --fix",
"git add"
],
"*.vue": [
"prettier-eslint --write",
"eslint --fix",
"git add"
],
"*.es6": [
"prettier-eslint --write",
"eslint --fix",
"git add"
]
}
1.6 配置 commitlint.config.js
module.exports = {
extends: ['@commitlint/config-conventional'],
rules: {
'type-enum': [
2,
'always', [
'add',
'update',
'delete',
'feat',
'fix',
'merge',
'chore',
'docs',
'style',
'refactor',
'perf',
'revert',
'test'
]
],
'subject-case': [0, 'never', ['lower-case']]
}
}
1.7 配置 .editorconfig (统一编辑器配置)
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 4
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
1.8 在 package.json 中配置 husky
"husky": {
"hooks": {
"commit-msg": "commitlint -E HUSKY_GIT_PARAMS",
"pre-commit": "lint-staged"
}
}
二、部署 stylelint 规范 CSS
2.1 安装依赖
npm i husky lint-staged stylelint stylelint-config-standard --save-dev
- stylelint-config-standard: stylelint 的标准规则。
2.2 配置 .stylelintrc.js
module.exports = {
"extends": ["stylelint-config-standard"],
// 插件
"plugins": [],
// 自定义规则
"rules": {}
};
2.3 在 package.json 中配置 husky
执行 git commit 之前会自动以 stylelint 的方式校验文件。
{
// ...
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
}
}
2.4 配置 .lintstagedrc
{
"src/**/*.css": [
"stylelint --fix",
"git add"
],
"src/**/*.less": [
"stylelint --fix",
"git add"
],
"src/**/*.scss": [
"stylelint --fix",
"git add"
]
}
stylelint --fix 会自动修改部分不规范代码,更多戳→How do I automatically fix stylistic violations?。
2.5 配置 .stylelintignore
指定需要忽略的文件。
**/node_modules/**
**/dist/**
**/output/**
**/library/**
2.6 Vue 项目额外配置
修改 .lintstagedrc
{
"src/**/*.css": [
"stylelint --fix",
"git add"
],
"src/**/*.less": [
"stylelint --fix",
"git add"
],
"src/**/*.scss": [
"stylelint --fix",
"git add"
],
"src/**/*.vue": [
"stylelint --fix",
"git add"
]
}
三、部署 htmllint 规范 HTML
3.1 安装依赖
npm i husky lint-staged htmllint --save-dev
3.2 配置 .htmllintrc
{
"plugins": [], // npm modules to load
"maxerr": false,
"raw-ignore-regex": false,
"attr-bans": [
"align",
"background",
"bgcolor",
"border",
"frameborder",
"longdesc",
"marginwidth",
"marginheight",
"scrolling",
"style",
"width"
],
"indent-delta": false,
"indent-style": "nonmixed",
"indent-width": 2,
"indent-width-cont": false,
"spec-char-escape": false,
"text-ignore-regex": false,
"tag-bans": [
"style",
"b"
],
"tag-close": true,
"tag-name-lowercase": true,
"tag-name-match": true,
"tag-self-close": false,
"doctype-first": false,
"doctype-html5": false,
"attr-name-style": false,
"attr-name-ignore-regex": false,
"attr-no-dup": true,
"attr-no-unsafe-char": true,
"attr-order": false,
"attr-quote-style": "double",
"attr-req-value": true,
"attr-new-line": false,
"attr-validate": false,
"id-no-dup": true,
"id-class-no-ad": true,
"id-class-style": false,
"class-no-dup": true,
"class-style": false,
"id-class-ignore-regex": false,
"img-req-alt": true,
"img-req-src": true,
"html-valid-content-model": true,
"head-valid-content-model": true,
"href-style": false,
"link-req-noopener": true,
"label-req-for": true,
"line-end-style": "lf",
"line-no-trailing-whitespace": true,
"line-max-len": false,
"line-max-len-ignore-regex": false,
"head-req-title": true,
"title-no-dup": true,
"title-max-len": 60,
"html-req-lang": false,
"lang-style": "case",
"fig-req-figcaption": false,
"focusable-tabindex-style": false,
"input-radio-req-name": true,
"input-req-label": false,
"table-req-caption": false,
"table-req-header": false,
"tag-req-attr": false
}
3.3 在 package.json 中配置 husky 和 lint-staged
{
// ...
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
}
}
3.4 配置 .lintstagedrc
{
"src/**/*.html": [
"htmllint",
"git add"
],
// Vue 项目额外配置
"src/**/*.vue": [
"htmllint",
"git add"
]
}
四、JavaScript 代码规范(仅供参考)
-
使用两个空格进行缩进。
eslint:
indentfunction hello (name) { console.log('hi', name) } -
除需要转义的情况外,字符串统一使用单引号。
eslint:
quotesconsole.log('hello there') $("")不要定义未使用的变量。
eslint:
no-unused-varsfunction myFunction () { var 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字符串拼接操作符 (Infix operators) 之间要留空格。
eslint:
space-infix-ops// ✓ ok var x = 2 var message = 'hello, ' + name + '!'// ✗ avoid var x=2 var message = 'hello, '+name+'!'逗号后面加空格。
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 关键字要与花括号保持在同一行。
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 var value = 'hello world' console.log(value)// ✗ avoid var value = 'hello world' console.log(value)对于三元运算符
?和:与他们所负责的代码处于同一行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'每个 var 关键字单独声明一个变量。
eslint:
one-var// ✓ ok var silent = true var verbose = true // ✗ avoid var silent = true, verbose = true // ✗ avoid var 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 var my_var = 'hello' // ✗ avoid var myVar = 'hello' // ✓ ok不允许有多余的行末逗号。
eslint:
comma-danglevar obj = { message: 'hello', // ✗ avoid }始终将逗号置于行末。
eslint:
comma-stylevar obj = { foo: 'foo' ,bar: 'bar' // ✗ avoid } var 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-spacingvar obj = { 'key' : 'value' } // ✗ avoid var obj = { 'key' :'value' } // ✗ avoid var obj = { 'key':'value' } // ✗ avoid var obj = { 'key': 'value' } // ✓ ok构造函数要以大写字母开头。
eslint:
new-capfunction animal () {} var dog = new animal() // ✗ avoid function Animal () {} var dog = new Animal() // ✓ ok无参的构造函数调用时要带上括号。
eslint:
new-parensfunction Animal () {} var dog = new Animal // ✗ avoid var dog = new Animal() // ✓ ok对象中定义了存值器,一定要对应的定义取值器。
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 } }子类的构造器中一定要调用
supereslint:
constructor-superclass Dog { constructor () { super() // ✗ avoid } } class Dog extends Mammal { constructor () { super() // ✓ ok } }使用数组字面量而不是构造器。
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避免使用常量作为条件表达式的条件(循环语句除外)。
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不要定义冗余的函数参数。
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-keysvar 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( "var result = user." + propName ) // ✗ avoid var result = user[propName] // ✓ okcatch中不要对错误重新赋值。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 () { } // ✓ okswitch一定要使用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 () /**/{} // ✗ avoid 禁止使用
__iterator__。eslint:
no-iteratorFoo.prototype.__iterator__ = function () {} // ✗ avoid外部变量不要与对象属性重名。
eslint:
no-label-varvar score = 100 function game () { score: while (true) { // ✗ avoid score -= 10 if (score > 0) continue score break } }不要使用标签语句。
eslint:
no-labelslabel: while (true) { break label // ✗ avoid }不要书写不必要的嵌套代码块。
eslint:
no-lone-blocksfunction myFunc () { { // ✗ avoid myOtherFunc() } } function myFunc () { myOtherFunc() // ✓ ok }不要混合使用空格与制表符作为缩进。
eslint:
no-mixed-spaces-and-tabs除了缩进,不要使用多个空格。
eslint:
no-multi-spacesconst id = 1234 // ✗ avoid const id = 1234 // ✓ ok不要使用多行字符串。
eslint:
no-multi-strconst message = 'Hello \ world' // ✗ avoidnew创建对象实例后需要赋值给变量。eslint:
no-newnew Character() // ✗ avoid const character = new Character() // ✓ ok禁止使用
Function构造器。eslint:
no-new-funcvar 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不要将全局对象的属性作为函数调用。
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/ // ✓ okreturn 语句中的赋值必需有括号包裹。
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-unmodified-loop-conditionfor (let i = 0; i < items.length; j++) {...} // ✗ avoid for (let i = 0; i < items.length; i++) {...} // ✓ ok如果有更好的实现,尽量不要使用三元表达式。
eslint:
no-unneeded-ternarylet score = val ? val : 0 // ✗ avoid let score = val || 0 // ✓ okreturn,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' // ✗ avoidimport, 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 () { })() // ✓ okyield *中的*前后都要有空格。eslint:
yield-star-spacingyield* increment() // ✗ avoid yield * increment() // ✓ ok请书写优雅的条件语句(avoid Yoda conditions)。
eslint:
yodaif (42 === age) { } // ✗ avoid if (age === 42) { } // ✓ ok五、CSS 代码规范(仅供参考)
@规则
在 @规则 前需要有空行(除了同名 @规则,第一个子节点)。
stylelint: at-rule-empty-line-before
// 反例 @import "var"; @import "mix"; .qtt { color: pink; @extend .foo; } // 正例 @import "var"; @import "mix"; .qtt { color: pink; @extend .foo; }@规则 名称需小写。
stylelint: at-rule-name-case
// 反例 @Charset 'UTF-8'; @mEdIa (min-width: 50em) {} // 正例 @charset 'UTF-8'; @media (min-width: 50em) {}@规则 名称后面需要一个空格。
stylelint: at-rule-name-space-after
// 反例 @charset"UTF-8"; @media (min-width: 700px) {} // 正例 @charset "UTF-8"; @media (min-width: 700px) {}@规则 的分号后需要换行。
stylelint: at-rule-semicolon-newline-after
// 反例 @import "var";@import "mix"; // 正例 @import "var"; @import "mix";块
{}在块
{}的闭括号}前不需要空行。stylelint: block-closing-brace-empty-line-before
// 反例 .qtt { display: flex; } // 正例 .qtt { display: flex; }在块
{}的闭括号}后需要换行。stylelint: block-closing-brace-newline-after
// 反例 div { color: pink; } .qtt { color: blue; } // 正例 div { color: pink; } .qtt { color: blue; }在多行代码块中的闭括号
}前需要有换行。stylelint: block-closing-brace-newline-before
// 反例 .qtt { color: pink; display: flex;} // 反例 .qtt { color: pink; display: flex; }在单行块中的闭括号
}前需要有一个空格。stylelint: block-closing-brace-space-before
// 反例 a { color: pink;} // 正例 a { color: pink; }在多行块中,开括号
{后必须始终有换行。stylelint: block-opening-brace-newline-after
// 反例 a { color: pink; display: flex; } // 正例 a { color: pink; display: flex; }在单行块中,开括号
{后必须始终有一个空格。stylelint: block-opening-brace-space-after
// 反例 a {color: pink; } // 正例 a { color: pink; }在开括号
{之前必须有一个空格。stylelint: block-opening-brace-space-before
// 反例 a{ color: pink; } // 正例 a { color: pink; }颜色
十六进制颜色需要是小写。
stylelint: color-hex-case
// 反例 a { color: #FFF; } // 正例 a { color: #fff; }十六进制颜色需要是短符号。
stylelint: color-hex-length
// 反例 a { color: #ffffff; } // 正例 a { color: #fff; }注释
注释前必须始终有一个空行(除了第一个子节点,忽略向 stylelint 传递命令的注释)。
stylelint: comment-empty-line-before
// 反例 a {} /* comment */ // 正例 a {} /* comment */注释内必须始终有空格。
stylelint: comment-whitespace-inside
// 反例 /*comment*/ // 正例 /* comment */自定义属性
在自定义属性之前需要空行(除了在另一个自定义属性后,或第一个子节点)。
stylelint: custom-property-empty-line-before
// 反例 a { display: flex; --foo: pink; --bar: blue; } // 正例 a { display: flex; --foo: pink; --bar: blue; }声明
!important中的!后面不需要空格。stylelint: declaration-bang-space-after
// 反例 a { color: pink ! important; } // 正例 a { color: pink !important; }!important中的!前面需要空格。stylelint: declaration-bang-space-before
// 反例 a { color: pink!important; } // 正例 a { color: pink !important; }在多行规则中,分号后面必须始终有换行。
stylelint: declaration-block-semicolon-newline-after
// 反例 a { color: pink; top: 0; } // 正例 a { color: pink; top: 0; }在单行声明块中,分号后面必须始终有一个空格。
stylelint: declaration-block-semicolon-space-after
// 反例 a { color: pink;} // 正例 a { color: pink; }分号前不能有空格。
stylelint: declaration-block-semicolon-space-before
// 反例 a { color: pink ; } // 正例 a { color: pink; }单行块中只能有一个声明。
stylelint: declaration-block-single-line-max-declarations
// 反例 a { color: pink; top: 3px; } // 正例 a { color: pink; }声明块结尾一定要有分号。
stylelint: declaration-block-trailing-semicolon
// 反例 a { color: pink } // 正例 a { color: pink; }如果声明的值是多行,则冒号后需要有换行。
stylelint: declaration-colon-newline-after
// 反例 a { box-shadow: 0 0 0 1px #5b9dd9, 0 0 2px 1px rgba(30, 140, 190, 0.8); } // 正例 a { box-shadow: 0 0 0 1px #5b9dd9, 0 0 2px 1px rgba(30, 140, 190, 0.8); }如果声明的值是单行的,则冒号后面需要有一个空格。
stylelint: declaration-colon-space-after
// 反例 a { box-shadow:0 0 0 1px #5b9dd9, 0 0 2px 1px rgba(30, 140, 190, 0.8); } // 正例 a { box-shadow: 0 0 0 1px #5b9dd9, 0 0 2px 1px rgba(30, 140, 190, 0.8); }冒号前不能有空格。
stylelint: declaration-colon-space-before
// 反例 a { color : pink; } // 正例 a { color: pink; }声明前需要空行(除了在另一个声明后,或第一个子节点)。
stylelint: declaration-empty-line-before
// 反例 a { @extend .qtt; bottom: 15px; top: 5px; } // 正例 a { @extend .qtt; bottom: 15px; top: 5px; }函数
在多行函数中,逗号后必须始终有换行。
stylelint: function-comma-newline-after
// 反例 a { transform: translate(1,1); } // 正例 a { transform: translate(1, 1); }在单行函数中,逗号后面必须始终有一个空格。
stylelint: function-comma-space-after
// 反例 a { transform: translate(1,1); } // 正例 a { transform: translate(1, 1); }函数的逗号前不能有空格。
stylelint: function-comma-space-before
// 反例 a { transform: translate(1 , 1); } // 正例 a { transform: translate(1, 1); }函数中相邻空行数为 0。
stylelint: function-max-empty-lines
// 反例 a { transform: translate( 1, 1 ); } // 正例 a { transform: translate( 1, 1 ); }函数名为小写。
stylelint: function-name-case
// 反例 a { width: Calc(5% - 10em); } // 正例 a { width: calc(5% - 10em); }多行函数的括号内必须始终有换行。
stylelint: function-parentheses-newline-inside
// 反例 a { transform: translate(1,1); } // 正例 a { transform: translate( 1, 1 ); }在单行函数的括号内决不能有空格。
stylelint: function-parentheses-space-inside
// 反例 a { transform: translate( 1, 1 ); } // 正例 a { transform: translate(1, 1); }函数后面需要有空格。
stylelint: function-whitespace-after
// 反例 a { transform: translate(1, 1)scale(3); } // 正例 a { transform: translate(1, 1) scale(3); }长度
不允许为 0 带长度单位。
stylelint: length-zero-no-unit
// 反例 a { top: 0px; } // 正例 a { top: 0; }媒体特性
冒号后面需要有一个空格。
stylelint: media-feature-colon-space-after
// 反例 @media (max-width:600px) {} // 正例 @media (max-width: 600px) {}冒号前不能有空格。
stylelint: media-feature-colon-space-before
// 反例 @media (max-width : 600px) {} // 正例 @media (max-width: 600px) {}媒体特性名称需要是小写。
stylelint: media-feature-name-case
// 反例 @media (MIN-WIDTH: 700px) {} // 正例 @media (min-width: 700px) {}媒体特性的圆括号内不允许空格。
stylelint: media-feature-parentheses-space-inside
// 反例 @media ( max-width: 300px ) {} // 正例 @media (max-width: 300px) {}在操作符之后必须始终有一个空格。
stylelint: media-feature-range-operator-space-after
// 反例 @media (width >=600px) {} // 正例 @media (width >= 600px) {}在操作符之前必须始终有一个空格。
stylelint: media-feature-range-operator-space-before
// 反例 @media (width>= 600px) {} // 正例 @media (width >= 600px) {}在多行媒体查询列表中,逗号后必须始终有换行。
stylelint: media-query-list-comma-newline-after
// 反例 @media screen and (color),projection and (color) {} // 正例 @media screen and (color), projection and (color) {}在单行媒体查询列表中,逗号后面必须始终有一个空格。
stylelint: media-query-list-comma-space-after
// 反例 @media screen and (color),projection and (color) {} // 正例 @media screen and (color), projection and (color) {}在媒体查询列表的逗号之前不需要空格。
stylelint: media-query-list-comma-space-before
// 反例 @media screen and (color) , projection and (color) {} // 正例 @media screen and (color), projection and (color) {}数字
对于小于 1 的小数,需要前导零。
stylelint: number-leading-zero
// 反例 a { line-height: .5; } // 正例 a { line-height: 0.5; }不允许在数字后面加 0。
stylelint: number-no-trailing-zeros
// 反例 a { top: 1.0px; } // 正例 a { top: 1px; }属性
属性名为小写。
stylelint: property-case
// 反例 a { Width: 1px; } // 正例 a { width: 1px; }规则
在多行规则之前必须始终有一个空行(除非是第一个节点)。
stylelint: rule-empty-line-before
// 反例 @media { a {} b {} } // 正例 @media { a {} b {} }选择器
在属性选择器内的括号内不需要空白。
stylelint: selector-attribute-brackets-space-inside
// 反例 [ target] {} // 正例 [target] {}在属性选择器中的操作符之后不需要空格。
stylelint: selector-attribute-operator-space-after
// 反例 [target= _blank] {} // 正例 [target=_blank] {}在属性选择器中的操作符之前不需要空格。
stylelint: selector-attribute-operator-space-before
// 反例 [target =_blank] {} // 正例 [target=_blank] {}在选择器的组合符之后需要一个空格。
stylelint: selector-combinator-space-after
// 反例 a +b { color: pink; } // 正例 a + b { color: pink; }在选择器的组合子之前需要一个空格。
stylelint: selector-combinator-space-before
// 反例 a+ b { color: pink; } // 正例 a + b { color: pink; }不允许选择器的后代组合子使用非空格字符。
stylelint: selector-descendant-combinator-no-non-space
// 反例 .foo .bar {} // 正例 .foo .bar {}在选择器列表的逗号后需要换行符。
stylelint: selector-list-comma-newline-after
// 反例 a, b { color: pink; } // 正例 a, b { color: pink; }在选择器列表的逗号之前不允许空格。
stylelint: selector-list-comma-space-before
// 反例 a , b { color: pink; } // 正例 a, b { color: pink; }选择器中相邻空行数为 0。
stylelint: selector-max-empty-lines
// 反例 a, b { color: red; } // 正例 a, b { color: red; }伪类选择器需要是小写。
stylelint: selector-pseudo-class-case
// 反例 a:Hover {} // 正例 a:hover {}伪类选择器内的圆括号内不需要空格。
stylelint: selector-pseudo-class-parentheses-space-inside
// 反例 input:not( [type="submit"] ) {} // 正例 input:not([type="submit"]) {}伪元素选择器需要是小写。
stylelint: selector-pseudo-element-case
// 反例 a:Before {} // 正例 a:before {}适用的伪元素必须始终使用双冒号表示法。
stylelint: selector-pseudo-element-colon-notation
// 反例 a:before { color: pink; } // 正例 a::before { color: pink; }类型选择器需要是小写。
stylelint: selector-type-case
// 反例 A {} // 正例 a {}单位
单位需要是小写。
stylelint: unit-case
// 反例 a { width: 10PX; } // 正例 a { width: 10px; }值列表
在多行值列表中,逗号后必须始终有换行。
stylelint: value-list-comma-newline-after
// 反例 a { background-size: 0 ,0; } // 正例 a { background-size: 0, 0; }在单行值列表中,逗号后面必须始终有一个空格。
stylelint: value-list-comma-space-after
// 反例 a { background-size: 0,0; } // 正例 a { background-size: 0, 0; }在值列表的逗号之前不允许空格。
stylelint: value-list-comma-space-before
// 反例 a { background-size: 0 , 0; } // 正例 a { background-size: 0, 0; }限制值列表中相邻空行数为 0。
stylelint: value-list-max-empty-lines
// 反例 a { padding: 10px 10px 10px 10px; } // 正例 a { padding: 10px 10px 10px 10px; }General / Sheet
缩进 2 个空格。
stylelint: indentation
// 反例 @media print { a { background-position: top left, top right; } } // 正例 @media print { a { background-position: top left, top right; } }相邻空行最多为 1。
stylelint: max-empty-lines
// 反例 a {} b {} // 正例 a {} b {}不允许行尾空白。
stylelint: no-eol-whitespace
// 反例 a { color: pink; } /* ←空白 */ // 正例 a { color: pink; }/* ←没有空白 */需要有结束换行符。
stylelint: no-missing-end-of-source-newline
// 反例 a { color: pink; }/* ↓没有结束换行符\n */ // 正例 a { color: pink; } /* ←有结束换行符\n */版权声明
本博客所有的原创文章,作者皆保留版权。转载必须包含本声明,保持本文完整,并以超链接形式注明作者后除和本文原始地址:http://blog.mazey.net/1528.html