代码React NativeReact Native

如何配置Eslint检测React代码

2016-06-09  本文已影响11962人  超级大柱子

1.Eslint介绍

Eslint 是一个JavaScript验证工具,有了它可以让你的编辑器像ide一样进行一些静态的错误提示功能.

多打了一个分号 应该打冒号的地方打成了赋值符号 并没有找到变量bbb 返回的组件为空

2.编辑器安装Eslint插件

3.npm安装相关组件

安装linter

$ npm install linter

安装eslint

$ npm install eslint -g

安装eslint-plugin-react(不用加-g)

识别react中的一些语法检验
$ npm install eslint-plugin-react

安装babel-eslint

如果用到了es6的新语法, 需要安装babel-eslint,不然会把箭头函数识别成错误
$ npm install babel-eslint

4.在项目的根目录创建配置文件.eslintrc.json

eslint会根据.eslintrc.json定义的规则进行代码检测(在mac中的.开头的文件为隐藏文件);
eslint官方给出的一些有关react配置的文档:
https://github.com/yannickcr/eslint-plugin-react

一般有两种做法:

  1. 宽松的定义,只检验一些语法上的错误.
  2. 严谨的定义,可以当团队书写代码的规范,把规范错误定义成警告, 语法错误定义成错误

我自己用的是相对宽松的定义,定义如下:

{
    //文件名 .eslintrc.json
    "env": {
        "browser": true,
        "es6": true,
        "node": true,
        "commonjs": true
    },
    "extends": "eslint:recommended",
    "installedESLint": true,
    "parserOptions": {
        "ecmaFeatures": {
            "experimentalObjectRestSpread": true,
            "jsx": true,
            "arrowFunctions": true,
            "classes": true,
            "modules": true,
            "defaultParams": true
        },
        "sourceType": "module"
    },
    "parser": "babel-eslint",
    "plugins": [
        "react"
    ],
    "rules": {
        "linebreak-style": [
            "error",
            "unix"
        ],
        //"semi": ["error", "always"],
        "no-empty": 0,
        "comma-dangle": 0,
        "no-unused-vars": 0,
        "no-console": 0,
        "no-const-assign": 2,
        "no-dupe-class-members": 2,
        "no-duplicate-case": 2,
        "no-extra-parens": [2, "functions"],
        "no-self-compare": 2,
        "accessor-pairs": 2,
        "comma-spacing": [2, {
            "before": false,
            "after": true
        }],
        "constructor-super": 2,
        "new-cap": [2, {
            "newIsCap": true,
            "capIsNew": false
        }],
        "new-parens": 2,
        "no-array-constructor": 2,
        "no-class-assign": 2,
        "no-cond-assign": 2
    }
}

上一篇下一篇

猜你喜欢

热点阅读