webpack eslint

代码规范

ESLint 的必要性

2017年4⽉13日,腾讯⾼级⼯程师小明在做充值业务时,修改了苹果 iap ⽀付配置,将 JSON 配置增加了重复的 key 。代码发布后,有小部分使用了 vivo 手机的用户反馈充值页面白屏,无法在 Now app 内进行充值。最后问题定位是: vivo ⼿机使用了系统⾃带的 webview ⽽没有使用 X5 内核,解析 JSON 时遇到 重复 key 报错,导致⻚面白屏。

行业里面优秀的 ESLInt 规范实践

Airbnb: eslint-config-airbnb | eslint-config-airbnb-base

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

npm install eslint eslint-plugin-import eslint-plugin-react eslint-plugin-react-hooks eslint-plugin-jsx-a11y -D
npm install eslint-loader -D
npm install babel-eslint -D
npm install eslint-config-airbnb -D

然后在webpack.prod.js里面,对module 里面的 rule 数组里,针对 js 文件加入'eslint-loader'

创建 .eslintrc.js 文件

module.exports = {
  "parser": "babel-eslint",
  "extends": "airbnb",
  "env": {
    "browser": true,
    "node": true
  }
  "rules": {
    "semi": "error"  	
  },
}

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 配置并 改进

能够帮助发现代码错误的规则,全部开启

帮助保持团队的代码⻛风格统⼀一,⽽而不不是限制开发 体验

规则名称 错误级别 说明
for-direction error for的循环方向必须正确
getter-return error getter必须有返回值,并且禁止返回值为 undefined,比如 return;
no-wait-in-loop off 允许在循环里面使用await
no-console off 允许在代码里面使用 console
no-prototype-builtins warn 直接调用原型上的方法
valid-jsdoc off 函数注释一定要遵循 jsdoc规则
no-template-curly-in-string warn 字符串里面出现{和}警告
accessor-paris warn getter和 setter没有成对出现时给出警告
array-callback-return error 对于数据相关操作函数比如 reduce、map、filter等,callback 必须有return
block-scoped-var error 把关键字 var 看成块级作用域,防止变量提升的 bug
class-mothods-use-this error 要求在 class里面合理使用 this,如果某个方法没有使用 this,则应该声明为静态方法
complexity off 关闭代码复杂度限制
default-case error switch-case 里面要有 default分支

ESlint 如何执行落地

  • 和 CI / CD系统集成

  • 和 webpack 集成

方案一: webpack 与 CI / CD集成

在 build 前面加了一个 lint pipline

本地开发阶段增加 precommit 钩⼦子

安装 husky

npm install husky --save-dev

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

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

方案二:webpack 与 ESLint 集成

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

module.exports = {
  module: {
    rules: [
      {
        test:/.js$/,
        exclude: /node_modules/,
        use: [
          "babel-loader",
          "eslint-loader"
        ]
      }
    ]
  }
};
原文地址:https://www.cnblogs.com/ssaylo/p/13677807.html