Webpack系列——EsLint 在 Webpack 中的配置

项目中安装 EsLint :

npm install eslint -S

快速生成 EsLint 的配置文件:

npx eslint --init

运行命令后根据相关选项进行设定,成功操作后会在 src 下看到名为 .eslintrc.js的配置文件,在配置文件中可进行相关语法规范规则的编写。

.eslintrc.js

module.exports = {
    "extends": "airbnb",
    "parser": "babel-eslint"
}

babel-eslint需先 npm install babel-eslint -S安装

可以在命令行中运行 npm eslint src检验 src 下的文件语法

在 webpack 中配置EsLint :

安装 eslint-loader

npm install eslint-loader --save-dev

webpack.config.js

module.exports = {
    mode: 'development',
    //...
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: ['babel-loader', 'eslint-loader']
            }
        ]
    }
}

在运行打包命令后,会在控制台输出相关的语法错误提示信息。

可以在 devServer 配置项中进行配置 overlay: true,一旦出现语法错误,会在浏览器中弹出蒙层,蒙层上显示相关的语法错误信息。

module.exports = {
    mode: 'development',
    //...
    devServer: {
        contentBase: './dist',
        open: true,
        port: 8080,
        hot: true,
        overlay: true
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: ['babel-loader', 'eslint-loader']
            }
        ]
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先,你需要安装 `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、付费专栏及课程。

余额充值