Hibop / Hibop.github.io

Hibop 个人博客
https://hibop.github.io/
23 stars 1 forks source link

关于前端代码风格统一:eslint使用总结 #34

Open Hibop opened 6 years ago

Hibop commented 6 years ago

eslint是一个开源的JavaScript代码检查工具,作者Nicholas C. Zakas(大名鼎鼎的“红宝书”《JavaScript高级程序设计》作者 )。eslint就是用来统一JavaScript代码风格的工具:

  • 支持ES6、JSX、 Angular、Style、React、Vue等等;
  • 统一代码风格,减少review成本和低级错误的出现: 开发环境中,开发者每次修改代码,都会先用eslint检查代码,再进行babel和react的编译,减少了我们花费在review代码风格上的时间,降低了低级bug的出现。
  • 插件(plugin)和扩展(extend)丰富:
  • react ===> jsx和react 这两个插件
  • "extends": "eslint:recommended"
  • "extends": "airbnb" (airbnb 的规则)

环境配置:

  1. 引入eslint基础包: npm/yarn install eslint -D

  2. 让webpack知道pre-loader插件eslint-loader: npm/yarn install eslint-loader -D;

  3. 此时启动, eslint还不知道通过babel使用的es6特性: npm/yarn install babel-eslint -D; 并在配置文件中 { parser: 'babel-eslint', }

  4. .eslintrc文件进行配置

  5. 文件中禁止检测某一行: / eslint-disable no-unused-vars /

  6. 使用npm pre-commit钩子在git commit时自动检测代码规范

webpack的相关配置:

preLoaders: [
    {
        test: /\.js$/,  // 检测所有的js文件
        loader: "eslint-loader", // 使用eslint插件
        exclude: [   // 排除第三方文件
            /node_modules/,
            /app\/lib/
        ]
    }
]

注意:由于webpack在默认配置下遇到error并不会抛出错误终止代码打包,需要在webpack命令上添加bail参数让webpack抛出错误:

webpack --bail --progress --colors --config webpack.config.js

一般.eslintrc主要组成:

{
  "extends": "airbnb",  
  "parser": "babel-eslint",
  "plugins": ["vue"],
  "env": {
    "es6": true
  },
  "parserOptions": {
    "sourceType": "module",
  },
  "globals": {
    "PUBLIC": true
  },
  "rules": {
    "no-console": "warn"
  }
}

主要关注点主要三个:

规则格式是"<规则名称>: <告警级别>",告警级别分为三种:

此外的有几个比较重要的配置:

常用有用规则:

  1. 缩进空格:

    // 4空格缩进和switch下case4空格
    "indent": ["warn", 4, {
    "SwitchCase": 1
    }]
  2. 在条件判断中不能出现赋值语句:"no-cond-assign": "error" if ( a=1 ) { }

  3. 消除魔幻数字no-magic-numbers :将意义不明的数字声明为意义明确的常量,常量名称能让代码自注释,从而提高了代码的可读性

    "no-magic-numbers": ["error", {
    "ignoreArrayIndexes": true,  //  排除数组下标报错
    "ignore": [0, 1],   // 排除二进制
     "enforceConst": true   // 必须const声明常量, 一般大写
    }]
  4. 限制函数的最大参数个数"max-params": ["error", 4];

  5. 箭头回调函数优先,回调函数常常会遇到this引用的指向问题 :"prefer-arrow-callback": "warn";

  6. 模版优先: "prefer-template": "error";

  7. 禁用var关键字: "no-var": "error"

  8. 消除不必要的类型转换: if(!!str)、Boolean(str) "no-extra-boolean-cast": "error"

  9. console、alert代码: "no-console": "warn" “no-alert”: "warn" no-else-return

  10. 使用=== eqeqeq: ["error", "always"]

  11. parseInt()始终使用基数以消除意想不到的后果: radix:‘always’

现有的几套通用规则:eslint官方提供了3种预安装包:

  1. eslint-config-google : Google标准

  2. eslint-config-airbnb : Airbnb 依赖eslint, eslint-plugin-import, eslint-plugin-react, and eslint-plugin-jsx-a11y等插件,并且对各个插件的版本有所要求。可以执行以下命令查看所依赖的版本:

    npm info "eslint-config-airbnb@latest" peerDependencies
  3. eslint-config-standard : Standard标准,它是一些前端工程师自定的标准。 执行以下shell

    npm install eslint-config-standard eslint-plugin-standard eslint-plugin-promise -g

目前来看,公认的最好的标准是Airbnb标准。建议全局安装这些标准,然后在你的.eslint配置文件中直接使用。

es6比较推荐的规范

格式、类型、对象、数组、函数

  1. 格式: 单引号string、两空格缩进、结尾分号、行尾非空格、括号前后空格、模板字符串

  2. no-undef, prefer-const, no-const-assign, no-var: 保证块级作用域; no-unused-vars: 禁止无用的声明

  3. object-shorthand

    
    const lukeSkywalker = 'demo'
    const atom = {
    value: 1,
    // good
    lukeSkywalker,
    // good
    addValue(value) {
    return atom.value + value;
    },

};


3. array-callback-return: 数组遍历方法(map/each/filter/some/reduce/every...)回调都有返回: 保证无副作用

4. prefer-destructuring: 尽可能使用解构。多种好处:默认值+pick数据等等

5.no-else-return
···
// good
function foo() {
  if (x) {
    return x;
  }

  return y;
}
···

参考链接:
1. [http://eslint.cn/](http://eslint.cn/)
Hibop commented 5 years ago

js 推荐规范

Airbnb JavaScript 风格指南() {

JavaScript最合理的方法 A mostly reasonable approach to JavaScript

注意: 这个指南假定你正在使用Babel, 并且需要你使用或等效的使用babel-preset-airbnb。 同时假定你在你的应用里安装了带有或等效的airbnb-browser-shimsshims/polyfills

Downloads Downloads ![Gitter](https://badges.gitter.im/Join Chat.svg)

这个指南支持的其他语言翻译版请看 Translation

Other Style Guides

目录

  1. Types
  2. References
  3. Objects
  4. Arrays
  5. Destructuring
  6. Strings
  7. Functions
  8. Arrow Functions
  9. Classes & Constructors
  10. Modules
  11. Iterators and Generators
  12. Properties
  13. Variables
  14. Hoisting
  15. Comparison Operators & Equality
  16. Blocks
  17. Comments
  18. Whitespace
  19. Commas
  20. Semicolons
  21. Type Casting & Coercion
  22. Naming Conventions
  23. Accessors
  24. Events
  25. jQuery
  26. ECMAScript 5 Compatibility
  27. ECMAScript 6+ (ES 2015+) Styles
  28. Testing
  29. Performance
  30. Resources
  31. In the Wild
  32. Translation
  33. The JavaScript Style Guide Guide
  34. Chat With Us About JavaScript
  35. Contributors
  36. License

Types

⬆ back to top

References

⬆ back to top

Objects

⬆ back to top

Arrays

⬆ back to top

Destructuring

⬆ back to top

Strings

⬆ back to top

Functions

⬆ back to top

Arrow Functions

⬆ back to top

Classes & Constructors

⬆ back to top

Modules

⬆ back to top

Iterators and Generators

⬆ back to top

Properties

⬆ back to top

Variables

⬆ back to top

Hoisting

⬆ back to top

Comparison Operators & Equality

⬆ back to top

Blocks

⬆ back to top

Control Statements

⬆ back to top

Comments

⬆ back to top

Whitespace

⬆ back to top

Commas

⬆ back to top

Semicolons

⬆ back to top

Type Casting & Coercion

⬆ back to top

Naming Conventions

⬆ back to top

Accessors

⬆ back to top

Events

jQuery

⬆ back to top

ES5 兼容性

⬆ back to top

ECMAScript 6+ (ES 2015+) Styles

  1. 箭头函数——Arrow Functions
  2. 类——Classes
  3. 对象缩写——Object Shorthand
  4. 对象简写——Object Concise
  5. 对象计算属性——Object Computed Properties
  6. 模板字符串——Template Strings
  7. 解构赋值——Destructuring
  8. 默认参数——Default Parameters
  9. Rest
  10. Array Spreads
  11. Let and Const
  12. 幂操作符——Exponentiation Operator
  13. 迭代器和生成器——Iterators and Generators
  14. 模块——Modules

    Why? 它还不是最终版, 他可能还有很多变化,或者被撤销。 我们想要用的是 JavaScript, 提议还不是JavaScript。

⬆ back to top

Standard Library

标准库中包含一些功能受损但是由于历史原因遗留的工具类

Testing

⬆ back to top

Performance

⬆ back to top

Resources

Learning ES6

Read This

Tools

Other Style Guides

Other Styles

Further Reading

Books

Blogs

Podcasts

⬆ back to top

In the Wild

This is a list of organizations that are using this style guide. Send us a pull request and we'll add you to the list.

⬆ back to top

Translation

This style guide is also available in other languages:

The JavaScript Style Guide Guide

Chat With Us About JavaScript

Contributors

License

(The MIT License)

Copyright (c) 2012 Airbnb

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

⬆ back to top

Amendments

We encourage you to fork this guide and change the rules to fit your team’s style guide. Below, you may list some amendments to the style guide. This allows you to periodically update your style guide without having to deal with merge conflicts.

};

Hibop commented 5 years ago

Airbnb CSS / Sass 指南

用更合理的方式写 CSS 和 Sass

翻译自 Airbnb CSS / Sass Styleguide

目录

  1. 术语
  2. CSS
  3. Sass

术语

规则声明

我们把一个(或一组)选择器和一组属性称之为 “规则声明”。举个例子:

.listing {
  font-size: 18px;
  line-height: 1.2;
}

选择器

在规则声明中,“选择器” 负责选取 DOM 树中的元素,这些元素将被定义的属性所修饰。选择器可以匹配 HTML 元素,也可以匹配一个元素的类名、ID, 或者元素拥有的属性。以下是选择器的例子:

.my-element-class {
  /* ... */
}

[aria-hidden] {
  /* ... */
}

属性

最后,属性决定了规则声明里被选择的元素将得到何种样式。属性以键值对形式存在,一个规则声明可以包含一或多个属性定义。以下是属性定义的例子:

/* some selector */ {
  background: #f1f1f1;
  color: #333;
}

CSS

格式

Bad

.avatar{
    border-radius:50%;
    border:2px solid white; }
.no, .nope, .not_good {
    // ...
}
#lol-no {
  // ...
}

Good

.avatar {
  border-radius: 50%;
  border: 2px solid white;
}

.one,
.selector,
.per-line {
  // ...
}

注释

OOCSS 和 BEM

出于以下原因,我们鼓励使用 OOCSS 和 BEM 的某种组合:

OOCSS,也就是 “Object Oriented CSS(面向对象的CSS)”,是一种写 CSS 的方法,其思想就是鼓励你把样式表看作“对象”的集合:创建可重用性、可重复性的代码段让你可以在整个网站中多次使用。

参考资料:

BEM,也就是 “Block-Element-Modifier”,是一种用于 HTML 和 CSS 类名的命名约定。BEM 最初是由 Yandex 提出的,要知道他们拥有巨大的代码库和可伸缩性,BEM 就是为此而生的,并且可以作为一套遵循 OOCSS 的参考指导规范。

示例

<article class="listing-card listing-card--featured">

  <h1 class="listing-card__title">Adorable 2BR in the sunny Mission</h1>

  <div class="listing-card__content">
    <p>Vestibulum id ligula porta felis euismod semper.</p>
  </div>

</article>
.listing-card { }
.listing-card--featured { }
.listing-card__title { }
.listing-card__content { }

ID 选择器

在 CSS 中,虽然可以通过 ID 选择元素,但大家通常都会把这种方式列为反面教材。ID 选择器给你的规则声明带来了不必要的高优先级,而且 ID 选择器是不可重用的。

想要了解关于这个主题的更多内容,参见 CSS Wizardry 的文章,文章中有关于如何处理优先级的内容。

JavaScript 钩子

避免在 CSS 和 JavaScript 中绑定相同的类。否则开发者在重构时通常会出现以下情况:轻则浪费时间在对照查找每个要改变的类,重则因为害怕破坏功能而不敢作出更改。

我们推荐在创建用于特定 JavaScript 的类名时,添加 .js- 前缀:

<button class="btn btn-primary js-request-to-book">Request to Book</button>

边框

在定义无边框样式时,使用 0 代替 none

Bad

.foo {
  border: none;
}

Good

.foo {
  border: 0;
}

Sass

语法

属性声明的排序

  1. 属性声明

    首先列出除去 @include 和嵌套选择器之外的所有属性声明。

    .btn-green {
      background: green;
      font-weight: bold;
      // ...
    }
  2. @include 声明

    紧随后面的是 @include,这样可以使得整个选择器的可读性更高。

    .btn-green {
      background: green;
      font-weight: bold;
      @include transition(background 0.5s ease);
      // ...
    }
  3. 嵌套选择器

    _如果有必要_用到嵌套选择器,把它们放到最后,在规则声明和嵌套选择器之间要加上空白,相邻嵌套选择器之间也要加上空白。嵌套选择器中的内容也要遵循上述指引。

    .btn {
      background: green;
      font-weight: bold;
      @include transition(background 0.5s ease);
    
      .icon {
        margin-right: 10px;
      }
    }

变量

变量名应使用破折号(例如 $my-variable)代替 camelCased 和 snake_cased 风格。对于仅用在当前文件的变量,可以在变量名之前添加下划线前缀(例如 $_my-variable)。

Mixins

为了让代码遵循 DRY 原则(Don't Repeat Yourself)、增强清晰性或抽象化复杂性,应该使用 mixin,这与那些命名良好的函数的作用是异曲同工的。虽然 mixin 可以不接收参数,但要注意,假如你不压缩负载(比如通过 gzip),这样会导致最终的样式包含不必要的代码重复。

扩展指令

应避免使用 @extend 指令,因为它并不直观,而且具有潜在风险,特别是用在嵌套选择器的时候。即便是在顶层占位符选择器使用扩展,如果选择器的顺序最终会改变,也可能会导致问题。(比如,如果它们存在于其他文件,而加载顺序发生了变化)。其实,使用 @extend 所获得的大部分优化效果,gzip 压缩已经帮助你做到了,因此你只需要通过 mixin 让样式表更符合 DRY 原则就足够了。

嵌套选择器

请不要让嵌套选择器的深度超过 3 层!

.page-container {
  .content {
    .profile {
      // STOP!
    }
  }
}

当遇到以上情况的时候,你也许是这样写 CSS 的:

再说一遍: 永远不要嵌套 ID 选择器!

如果你始终坚持要使用 ID 选择器(劝你三思),那也不应该嵌套它们。如果你正打算这么做,你需要先重新检查你的标签,或者指明原因。如果你想要写出风格良好的 HTML 和 CSS,你是应该这样做的。

ToruKiyono commented 3 months ago

eslint如何设置这个配置?

17.2 不要用选择操作符代替控制语句。