Eslint-Webpack-React

eslint 结合webpack 在React环境下的使用

检查代码的两种方式

  • 将eslint和代码编辑器相结合
  • 将eslint编码规范集成到构建工具(webpack)中

将eslint和代码编辑器相结合

在代码编辑器中直接下载eslint插件并安装,可以结合.editorconfig配置文件进行相关规范设置

将eslint编码规范集成到构建工具(webpack)中

  • 编辑器:vscode
  • package.json:
 "dependencies": {
    "react": "^15.6.1",
    "react-dom": "^15.6.1",
    "react-router-dom": "^4.2.2"
  },
  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-eslint": "^8.0.1",
    "babel-loader": "^7.1.2",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "css-loader": "^0.28.7",
    "eslint": "^4.7.2",
    "eslint-config-airbnb": "^15.1.0",
    "eslint-loader": "^1.9.0",
    "eslint-plugin-import": "^2.7.0",
    "eslint-plugin-jsx-a11y": "^5.1.0",
    "eslint-plugin-react": "^7.4.0",
    "html-webpack-plugin": "^2.30.1",
    "postcss-loader": "^2.0.6",
    "style-loader": "^0.18.2",
    "url-loader": "^0.5.9",
    "webpack": "^3.6.0",
    "webpack-dev-server": "^2.8.2"
  }
  • .eslintrc.json:
{
    "parserOptions":{
        "ecmaVersion": 6, // 指定想要支持的javascript版本,这里6表示es6
        "sourceType": "module", // 默认为"script",代码是ECMAScript准则,则设置为"module"
        "ecmaFeatures": {
            "jsx": true // 启用JSX
        }
    },
    // 指定脚本的运行环境,支持定义多个
    "env": {
        "es6": true,
        "node": true,
        "browser": true
    },
    // 使用第三方airbnb
    "extends": "airbnb",
    // airbnb包括以下三个插件,插件名称可以省略eslint-plugin-前缀
    "plugins":[
        "react",
        "jsx-a11y",
        "import"
    ],
    "parser":"babel-eslint",
    // 定义自己的规则
    "rules": {
        "comma-dangle": ["error","never"], //禁止末尾逗号
        "jsx-a11y/href-no-hash": ["error", { "components": ["a"] }],
        "linebreak-style":0
    }
}
  • webpack.config.js配置
module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        enforce: 'pre',
        exclude: /node_modules/,
        include: appath,
        loader: require.resolve('eslint-loader'),
        options: {
          // fix: true
        }
      }
    ]
  },

注意:

  1. 使用第三方airbnb的三个插件时,jsx-a11y不能使用v6版本(貌似被移除了),后续官方可能会出解决方案。
  2. eslint自定义规则时如果不配置"linebreak-style":0,代码检测会报[eslint] Expected linebreaks to be 'LF' but found 'CRLF'. (linebreak-style)的错,网上有人说是不同系统间的问题,试了下,我没有解决。所以在配置中自定义为0,即关闭该项代码检测。
  3. webpack.config.js中需要配置eslint-loader为先执行的loader。

你可能感兴趣的:(Eslint-Webpack-React)