8

Webpack干货系列 | 在 Webpack 5 集成 ESLint 的方法 - 程序员优雅哥

 3 years ago
source link: https://www.cnblogs.com/youyacoder/p/16498260.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

程序员优雅哥(youyacoder)简介:十年程序员,呆过央企外企私企,做过前端后端架构。分享vue、Java等前后端技术和架构。
本文摘要:主要讲解运用Webpack 5 中集成 ESLint 的方法与步骤

ESLint 是前端 JS 代码检查常用的工具,使用 ESLint 可以使不同的开发人员遵循统一的开发规范、有统一的代码风格。关于 ESLint 的详细介绍,参考《ESLint是什么》一文。本文详细介绍如何在 webpack 5 中集成 ESLint。

1 安装依赖

在 webpack 4 中,ESLint 是通过 loader 的方式集成到 webpack 中的。在 webpack 5 中,是通过 plugins(插件)的形式进行集成。插件名称为 eslint-webpack-plugin。该插件又依赖 eslint 包,故需要安装两个开发依赖包:

yarn add eslint eslint-webpack-plugin -D

2 添加配置文件

在项目的根路径下添加 ESLint 的配置文件:.eslintrc.js:

module.exports = {
  env: {
    node: true,
    browser: true
  },
  extends: ['eslint:recommended'],
  parserOptions: {
    ecmaVersion: 6,
    sourceType: "module"
  },
  rules: {
    'no-var': 'error',
    'no-console': 'error'
  }
}

3 修改 webpack 配置

修改 webpack.config.js,首先在文件顶部引入插件:

const ESLintWebpackPlugin = require('eslint-webpack-plugin')

Webpack5 插件是通过构造函数方式提供的,引入该插件后,得到的是一个构造函数,通过 new来创建对象。插件配置在webpack 配置对象的 plugins节点下,该节点是一个数组,数组每个元素都是一个插件。配置如下:

...
const ESLintWebpackPlugin = require('eslint-webpack-plugin')

module.exports = {
  ...
  plugins: [
    new ESLintWebpackPlugin({
      context: path.resolve(__dirname, 'src')
    })
  ],
  ...
}

4 测试运行

执行之前配置的 webpack 编译打包命令:yarn build

此时会看到报错信息,因为 ESLInt 检查没有通过:

ERROR in 
xxxxxxx/Webpack_Learning/src/main.js
  12:1  error  Unexpected console statement  no-console
  15:1  error  Unexpected console statement  no-console

这是在main.js中有 console.log语句造成的。

修改 ESLint 的配置文件 .eslintrc.js中的规则配置,将 no-console关闭:

'no-console': 'off'

重新执行打包命令,成功。

今日优雅哥(youyacoder)学习结束,期待留言分享~~


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK