webpack进阶篇(二十四):在webpack中使用ESLint

说明

玩转webpack课程学习笔记。

ESLint 的必要性

比如:⼿机使⽤了系统⾃带的 webview ⽽没有使⽤ X5 内核,解析 JSON 时遇到重复 key 报错,导致⻚⾯⽩屏。

⾏业⾥⾯优秀的 ESLint 规范实践

Airbnb:eslint-config-airbnb、 eslint-config-airbnb-base https://github.com/airbnb/javascript/tree/master/packages/eslint-config-airbnb

alloyteam团队:eslint-config-alloy https://github.com/AlloyTeam/eslint-config-alloy

ivweb 团队:eslint-config-ivweb https://github.com/feflow/eslint-config-ivweb

制定团队的 ESLint 规范

  • 不重复造轮⼦,基于 eslint:recommend 配置并改进
  • 能够帮助发现代码错误的规则,全部开启
  • 帮助保持团队的代码⻛格统⼀,⽽不是限制开发体验

https://eslint.bootcss.com/docs/rules/

webpack进阶篇(二十四):在webpack中使用ESLint_第1张图片

ESLint 如何执⾏落地

⽅案⼀:webpack 与 CI/CD 集成

webpack进阶篇(二十四):在webpack中使用ESLint_第2张图片

本地开发阶段增加 precommit 钩⼦

1、安装 husky

npm install husky --save-dev

2、增加 npm script,通过 lint-staged 增量检查修改的⽂件

"scripts": {
  "precommit": "lint-staged"
},
"lint-staged": {
  "linters": {
    "*.{js,scss}": ["eslint --fix", "git add"]
  }
},

⽅案⼆:webpack 与 ESLint 集成

1、使⽤ eslint-loader,构建时检查 JS 规范

module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: [
          "babel-loader",
          "eslint-loader"
        ]
      }
    ]
  }
};

例子

1、打开https://github.com/airbnb/javascript/tree/master/packages/eslint-config-airbnb,可以看到下面这个

eslint-config-airbnb

Our default export contains all of our ESLint rules, including ECMAScript 6+ and React. It requires eslint, eslint-plugin-import, eslint-plugin-react, eslint-plugin-react-hooks, and eslint-plugin-jsx-a11y. If you don’t need React, see eslint-config-airbnb-base.

2、安装依赖

2.1、npm i eslint eslint-plugin-import eslint-plugin-react eslint-plugin-react-hooks and eslint-plugin-jsx-a11y -D

2.2、npm i eslint-loader -D

2.3、npm i babel-eslint -D

2.4、npm i eslint-config-airbnb -D

我使用的是这个版本,版本太高会报一些错误。

"eslint-config-airbnb": "^17.1.0",
"eslint-config-airbnb-base": "^13.1.0",
"eslint-loader": "^2.1.2",
"eslint-plugin-import": "^2.17.3",
"eslint-plugin-jsx-a11y": "^6.2.1",
"eslint-plugin-react": "^7.13.0",

3、修改webapck.prod.js配置

添加eslint-loader

rules: [
  {
    test: /.js$/,
    use: [
      'babel-loader',
      'eslint-loader'
    ]
  }
]

4、添加.eslintrc.js文件

配置官网请参考:https://eslint.bootcss.com/docs/user-guide/configuring

module.exports = {
  "parser": "babel-eslint",
  "extends": 'airbnb',
  "env": {
    "browser": true,
    "node": true
  },
  "rules": {
    "indent": ["error", 4]
  }
}

webpack进阶篇(二十四):在webpack中使用ESLint_第3张图片

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