webpack4系列教程(八):使用Eslint审查代码

前言:

本章内容,咱们在项目中加入eslint配置,来审查校验代码,这样可以避免一些比较低级的错误。而且在团队协做的时候,保持同一种风格和规范能提升代码的可读性,进而提升咱们的工做效率。javascript

安装:

eslint-config-standard 是一种较为成熟通用的代码审查规则,这样就不用咱们本身去定义规则了,使用起来很是方便,记住还须要安装一些依赖插件:html

npm install --save-dev eslint eslint-config-standard eslint-plugin-standard eslint-plugin-promise eslint-plugin-import eslint-plugin-node

配置:

在项目根目录下建立 .eslintrc 文件:vue

{
  "extends": "standard",
  "rules": {
    "no-new": "off"
  }
}

在vue项目中,.vue文件中的 script标签内的代码,eslint 是没法识别的,这时就须要使用插件: eslint-plugin-htmljava

npm i eslint-plugin-html -D

而后在 .eslintrc 中配置该插件:node

{
  "extends": "standard",
  "plugins": [
    "html"
  ],
  "rules": {
    "no-new": "off"
  }
}

这样就能解析 .vue文件中的JS代码了,官方也是如此推荐。webpack

使用:

配置完成,如何使用呢?
在 package.json 文件中添加一条 script:web

"scripts": {
    "build": "cross-env NODE_ENV=production webpack --config config/webpack.config.js --progress --inline --colors",
    "lint": "eslint --ext .js --ext .vue src/"
  }

- -ext 表明须要解析的文件格式,最后接上文件路径,因为咱们的主要代码都在src 目录下,这里就配置 src 文件夹。npm

npm run lint

可见控制台给出了不少错误:
在这里插入图片描述
在项目前期没有加入eslint的状况下,后期加入必然会审查出许多错误。出现这么多错误以后,若是咱们逐条手动去解决会很是耗时,此时能够借助eslint自动修复,方法也很简单。
只须要添加一条命令便可:json

"scripts": {
  "build": "cross-env NODE_ENV=production webpack --config config/webpack.config.js --progress --inline --colors",
  "lint": "eslint --ext .js --ext .vue src/",
  "lint-fix": "eslint --fix --ext .js --ext .jsx --ext .vue src/"
}

而后执行promise

npm run lint-fix

咱们但愿在开发过程当中可以实时进行eslint代码审查,须要安装两个依赖:

npm i eslint-loader babel-eslint -D

修改 .eslintrc

{
  "extends": "standard",
  "plugins": [
    "html"
  ],
  "rules": {
    "no-new": "off"
  },
  "parserOptions":{
    "parser": "babel-eslint"
  }
}

因为咱们的项目使用了webpack而且代码都是通过Babel编译的,可是Babel处理过的代码有些语法可能对于eslint支持性很差,因此须要指定一个 parser。
下一步,在webpack.config.js中添加loader:

{
        test: /\.(vue|js)$/,
        loader: 'eslint-loader',
        exclude: /node_modules/,
        enforce: 'pre'
 }

enforce: 'pre' 表示预处理,由于咱们只是但愿eslint来审查咱们的代码,并非去改变它,在真正的loader(好比:vue-loader)发挥做用前用eslint去检查代码。

记得在你的IDE中安装并开启eslint插件功能,这样就会有错误提示了。

好比:
在这里插入图片描述
图中的错误是未使用的变量。

# editorconfig:
editorconfig是用来规范咱们的IDE配置的,在根目录建立 .editorconfig文件:

root = true

[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true

这样就能在各类IDE使用相同的配置了。

一样须要在IDE中安装editorconfig插件

以上就是eslint的配置方法了。

相关文章
相关标签/搜索