ZoeyYoung / blog

博客
1 stars 0 forks source link

Code Style & ESLint #7

Open ZoeyYoung opened 8 years ago

ZoeyYoung commented 8 years ago

ESLint 是什么

The pluggable linting utility for JavaScript and JSX. http://eslint.org

关键词:支持插件扩展、配置可继承、可自定义规则、支持React/JSX/ES6

可配置的错误等级 error level

因为配置可继承,因此比较方便的使用方式是采用比较流行的风格指南,然后根据团队需求配置

比较火的代码风格指南: airbnb

其中包含了react/jsx风格指南:https://github.com/airbnb/javascript/tree/master/react

对应的ESLint配置:https://github.com/airbnb/javascript/tree/master/packages/eslint-config-airbnb

安装说明:

Our default export contains all of our ESLint rules, including EcmaScript 6+ and React. It requires eslint and eslint-plugin-react.

  1. npm install --save-dev eslint-config-airbnb eslint-plugin-react eslint
  2. add "extends": "airbnb" to your .eslintrc
    • 不想包含react lint时,继承"airbnb-base";
    • 不需要es6支持时,继承"airbnb-base/legacy";

      添加es7支持

npm install --save-dev babel-eslint

示例配置文件:.eslintrc(继承airbnb)

{
  "extends": "airbnb",
  "parser": "babel-eslint",
  "globals": {
    "__DEV__": true
  },
  "ecmaFeatures": {
    "experimentalObjectRestSpread": true
  },
  "rules": {
    "react/jsx-quotes": 0,
    "jsx-quotes": [2, "prefer-double"]
  }
}

忽略不想检测的文件

添加_.eslintignore_文件:

node_modules/*
build/*

输出html报告

  1. npm install -g eslint-config-airbnb eslint-plugin-react eslint babel-eslint
  2. eslint -f html src/** > eslint-report.html

可用报告形式:http://eslint.org/docs/user-guide/formatters/

项目的error、warning数统计

https://www.npmjs.com/package/eslint-stats

$ eslint --format node_modules/eslint-stats/byError.js src/**

可用报告:byError、byWarning、byErrorAndWarning、byErrorAndWarningStacked、byFolder

结合编辑器使用

Atom https://github.com/AtomLinter/linter-eslint

Sublime Text 参考: http://jonathancreamer.com/setup-eslint-with-es6-in-sublime-text/

其它集成:http://eslint.org/docs/user-guide/integrations

添加git hook

https://github.com/dwyl/learn-pre-commit

使用pre-commit库

npm i -D pre-commit

在package.json中添加配置

{
  ...
  "scripts": {
    "eslint": "eslint -c ./MyApp/.eslintrc $(git diff --cached --name-only | grep -e \\MyApp/src/.*.js$)"
  },
  "pre-commit": [
    "eslint"
  ],
  ...
}

关于eslint的博文

http://csspod.com/getting-started-with-eslint/

ZoeyYoung commented 8 years ago

https://npmsearch.com/?q=keywords:eslintconfig

star & fork 数最多的为 eslint-config-airbnb

ZoeyYoung commented 8 years ago

规则列表:http://eslint.org/docs/rules/ react rules查询:https://github.com/yannickcr/eslint-plugin-react

ZoeyYoung commented 8 years ago

关于为什么要编码规范的博文

为什么谷歌要执行严格的代码编写规范

ZoeyYoung commented 8 years ago

编码风格每个人的喜好是会有所不同的,随便列出几个能想到的:

比较同意的观点是以项目为主,如果一个项目约定了某种风格,就使用那种风格就好了,这种时候就不要太个性了,特别是开源项目,要尊重别人的风格;

虽然有格式强迫症,但唯一不能接受的就是同一个项目中风格上的不一致,而非风格上与自己的喜好不符;

比如说缩进4个空格与缩进两个空格,混用TAB、空格这种情况真实在最近参与的项目中出现,当时的内心几乎是崩溃的;(现在已经彻底改造了 :blush: )