# 使用ESlint提高代码质量

# ESLint介绍

ESLint 是一个插件化的 javascript 代码检测工具,它可以用于检查常见的 JavaScript 代码错误,也可以进行代码风格检查,实现辅助编码规范的执行,有效控制项目代码的质量。使用ESLint规范将表明代码的简明性及团队的约定要高于个人的编码风格,不一定100%适用于所有项目和多元的编程文化,每个团队都应根据自己的的实际情况来定制不同的东西,CYB支持在项目中灵活自定义规则或整合第三方规则。

# 在CYB中使用ESlint

TIP

CYB放弃了高度集成ESlint的封闭模式,交予项目自行安装eslint核心及扩展包,这种开放的原则让功能的使用和扩展更加灵活。

# 开始使用

1、安装npm依赖包

npm i --save-dev eslint eslint-loader eslint-friendly-formatter

2、项目根目录新建webpack.config.eslint.js文件

// webpack.config.eslint.js

const eslintFriendlyFormatter = require('eslint-friendly-formatter')
const config = require('./cyb.config.js')

const eslintLoader = () => ({
  test: /\.(js|vue)$/,
  loader: 'eslint-loader',
  enforce: 'pre',
  exclude: /(node_modules|bower_components)/,
  options: {
    formatter: eslintFriendlyFormatter,
    emitWarning: true
  }
})

module.exports = {
  module: {
    rules: [
      ...(config.eslint.available ? [eslintLoader()] : [])
    ]
  }
}

使用CYB构建的项目支持以webpack.config*.js命名的webpack扩展配置,即可以将webpack.config.eslint.js中的配置合并到webpack.config.js文件中。

3、在cyb.config.js中配置启用开关

//cyb.config.js
export default {
  /**
   * 使用eslint检测代码
   */
  eslint: {
    available: false
  }
}

4、根目录下新建.eslintrc.js

/**
 * ---------------------------------
 * eslint配置文件,具体配置请参考:
 * https://eslint.org/docs/user-guide/configuring
 */

module.exports = {
    root: true,
    parserOptions: {
        ecmaVersion: 6,
        sourceType: 'module',
        parser: 'babel-eslint'
    },
    /**
     * 预定义全局变量
     * http://eslint.cn/docs/user-guide/configuring#specifying-environments
     */
    env: {
        browser: true,
        node: true,
        commonjs: true,
        es6: true
    },
    extends: [],
    plugins: [],
    rules: {
    }
}

根据项目情况可以自行安装eslint扩展,并在.eslintrc.js配置规则。

# 配置指南

http://eslint.cn/docs/user-guide/configuring