【Webpack】语法检查 eslint


1、js 代码的语法检查

  1. npm 添加依赖,一共需要下载4个依赖
npm i eslint eslint-loader eslint-plugin-import eslint-config-airbnb-base -D
  1. 在 webpack.config.js 中添加配置
module: {
    rules: [
      /* 加载 eslint 语法检查*/
      {
        test:/\.js$/,
         /* 只检查自己的源代码,不检查第三方库 */
        exclude:/node_modules/,
        loader:'eslint-loader',
        options:{
            /* 自动修复 */
            fix:true
        }
      }
    ],
  },
  1. 在 package.json 中添加检查规范
"eslintConfig":{
    "extends": "airbnb-base"
  }

2、js 的兼容性处理

  1. 基础的 js 兼容性处理 @babel/preset-env

npm 添加依赖,一共需要下载2个依赖

npm i babel-loader @babel/preset-env -D

在 webpack.config.js 中添加配置

module: {
    rules: [
      {
        test:/\.js$/,
         /* 只检查自己的源代码,不检查第三方库 */
        exclude:/node_modules/,
        loader:'babel-loader',
        options:{
            /* 基础的 js 兼容性处理 @babel/preset-env */
            /* 预设:指示怎么做 babel 兼容性处理 */
            preset:['@babel/preset-env']
        }
      }
    ],
  },
  1. 全部的 js 兼容性处理 @babel/polyfill

npm 添加依赖

npm i @babel/polyfill -D

只需在 js 文件引入即可,但是会导致体积太大

import '@babel/polyfill'
  1. 按需加载兼容性处理 core.js

npm 添加依赖

npm i core.js -D

在 webpack.config.js 中添加配置

module: {
    rules: [
       {
        test:/\.js$/,
        exclude:/node_modules/,
        loader:'babel-loader',
        options:{
            preset:[
                [
                    '@babel/preset-env',
                    {
                        //按需加载
                        useBuiltIns:'usage',
                        //指定 core 版本
                        corejs:{
                            version:3
                        },
                        //指定兼容性到浏览器的哪个版本
                        targets:{
                            chrome:'60',
                            firefox:'60'
                        }
                    }
                ]
            ]
        }
      }
    ],
  },

按需加载兼容不能和全部兼容一起使用

相关