ESlint 简单使用

5,801 阅读1分钟
原文链接: sunyongjian.github.io

开始

eslint是在 ECMAScript/JavaScript 代码中识别和报告模式匹配的工具,它的目标是保证代码的一致性和避免错误。(官方翻译)

两种安装方式

  • 全局

适用于所有项目文件

先全局安装ESLint插件

$ npm install -g eslint

初始化配置文件

eslint --init

使用

eslint file.js

  • 本地
    项目里使用
    npm install eslint --save-dev

react plugins

npm install --save-dev eslint-plugin-react

目前项目中用的airbnb代码规范

npm install --save-dev eslint-config-airbnb

项目中初始化配置文件

./node_modules/.bin/eslint --init

然后选择使用airbnb的方式

? How would you like to configure ESLint? Use a popular style guide? Which style guide do you want to follow? AirBnB? What format do you want your config file to be in? JavaScript

运行

./node_modules/.bin/eslint file.js

autofix

只支持空格分号等
链接

./node_modules/.bin/eslint file.js --fix

配置文件

  • init 初始化配置文件后,项目中会得到一个.eslintrc.js的文件。当然还会有.json YAML等格式的。

    module.exports = {    "extends": "airbnb",//拓展规则    "plugins": [//插件          "react",          "jsx-a11y",          "import"    ],    "env": {//指定环境      "browser": true,      "node": true    },     "rules": {//规则        "semi": "error"    }}
  • package.json中使用

    "name": "mypackage","version": "0.0.1","eslintConfig": {    "plugins": ["react"],    "env": {        "browser": true    }}

Rules

  • “off” 或 0 - 关闭规则
  • “warn” 或 1 - 开启规则,使用警告级别的错误:warn (不会导致程序退出)
  • “error” 或 2 - 开启规则,使用错误级别的错误:error (当被触发的时候,程序会退出)

如果采用了拓展规则,比如说airbnb,会有默认的,再node_module中都有rules,那配置文件就不用再多写了。但是我们可以写一些,覆盖拓展里的,以达到关闭某些规则的作用。
例如
这些规则都可以google一下

"rules": {  "react/jsx-filename-extension": [1, { "extensions": [".js", ".jsx"] }],  "react/forbid-prop-types": 0,  "react/no-array-index-key": 0,  "react/jsx-wrap-multilines": 0,  "react/prop-types": 1,  "jsx-a11y/no-static-element-interactions": 0,  "no-underscore-dangle": 0,  "no-script-url": 0,  "class-methods-use-this": 0,  "no-constant-condition": 0,  "max-len": 0,  "no-nested-ternary": 0,  "semi": 1,  "space-before-function-paren": 1}

.eslintignore

可以在项目根目录创建,告诉ESLint忽略某些文件或者目录。相当于.gitignore都是纯文本文件。
例如

# 注释,忽略文件node_modules**/.jsbuild

配合webpack的使用

安装一个eslint-loader 的loader

module:{  preLoaders: [      {test: /\.js$/, loader: "eslint-loader", exclude: /node_modules/}    ],  loaders:[   {       test:/\.jsx?$/,     exclude:/node_modules/,     loader:'babel'  },  {       test:/\.css$/,      loaders:['style','css'],        include:'/dist' }]}

结合pre-commit使用

有时候可能我们的项目后入eslint,之前的文件太多,改不过来,但是却要慢慢加入。可以加一个git的hooks。

  • 项目本地安装

    npm install --save-dev pre-commit
  • package.json配置

例如

{    "script": {        "lint": "git diff-tree --no-commit-id --name-only -r $REVISION | xargs pre-commit run --files."    },    "pre-commit": [        "lint"    ],}

pre-commit

  • git钩子(可自定义)
    钩子都被存储在Git目录下的hooks目录中
    cd .git/hooks && ls

这些钩子的功能主要分为提交工作流钩子、电子邮件工作流钩子和其它钩子。比如提交代码之前检查,提交给同组开发人员发邮件等等。

git hooks

当然eslint也可以结合gulp,以及在编译器中使用。这些从网上都可以查到。比如我现在atom用到的就直接下载bao包了

apm install linter-eslint