webpack中利用eslint对js进行代码格式检校

本文介绍了如何在Webpack中集成Eslint进行JavaScript代码格式检查。通过下载相关插件,配置webpack.config.js和package.json,实现代码打包时的格式验证。当遇到无法自动修复的错误或合理但被误报的代码时,可以使用eslint注释`eslint-disable-next-line`跳过特定行的检查。
摘要由CSDN通过智能技术生成

1.下载多个相关插件

npm i -D eslint eslint-config-airbnb-base eslint-webpack-plugin eslint-plugin-import

2.webpack.config.js中进行引用,并实例化

const ESLintPlugin = require('eslint-webpack-plugin')
 new ESLintPlugin()

3.配置package.json

"eslintConfig": {
    "extends": "airbnb-base"
  }
//添加扩展库

4.运行webpack进行打包,配置已生效会出现很多js格式错误

ERROR in
D:\Webpack\03-webpackcss\src\index.js
   1:24  error  Expected linebreaks to be 'LF' but found 'CRLF'      linebreak-style
   1:24  error  Missing semicolon                                    semi
   2:1   error  Expected linebreaks to be 'LF' but found 'CRLF'      linebreak-style
   3:28  error  Expected linebreaks to be 'LF' but found 'CRLF'      linebreak-style
   4:23  error  Expected linebreaks to be 'LF' but found 'CRLF
首先,你需要安装 `eslint-config-standard` 和 `eslint-plugin-standard`。 ``` npm install eslint-config-standard eslint-plugin-standard --save-dev ``` 然后,在你的webpack配置文件添加eslint配置。 ```javascript module.exports = { // ... other configurations module: { rules: [ { test: /\.js$/, loader: 'eslint-loader', enforce: 'pre', include: [path.resolve(__dirname, 'src')], // 指定检查的目录 options: { formatter: require('eslint-friendly-formatter'), // 指定错误报告的格式规范 eslintPath: require.resolve('eslint'), configFile: '.eslintrc.json', // 指定eslint配置文件路径 plugins: ['standard'], // 配置eslint插件 globals: [], // 声明全局变量 rules: { 'no-console': 'error', // 禁止使用console 'no-debugger': 'error', // 禁止使用debugger 'no-alert': 'error', // 禁止使用alert 'no-unused-vars': 'error', // 禁止未使用的变量 'standard/no-callback-literal': 'error' // 禁止在回调函数直接使用字面量 } } }, // ... other loaders ] } } ``` 最后,你需要在项目根目录下创建 `.eslintrc.json` 文件,并进行以下配置: ```json { "extends": [ "standard" ], "env": { "browser": true, "node": true, "es6": true }, "parserOptions": { "ecmaVersion": 2020, "sourceType": "module" }, "rules": { "semi": ["error", "always"], "quotes": ["error", "single"] } } ``` 上述配置表示,我们使用 `standard` 规则集进行代码检查,支持浏览器和 node.js 环境,使用 ECMAScript 2020 版本,强制使用分号和单引号。 这样,你就可以在开发过程使用 `eslint-loader` 进行代码检查了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值