blog icon indicating copy to clipboard operation
blog copied to clipboard

webpack 配置babel,转化ES6 新的api

Open xianzou opened this issue 5 years ago • 0 comments

前置条件

安装babel-loader: yarn add -D babel-loader;

配置webpack.config.js:

module: {
    rules: [
        {
            test: /\.js$/, use: 'babel-loader'
        }
    ]
}

方法一

安装依赖:

yarn add -D @babel/polyfill;

在主入口引入模块:

import 'babel-polyfill';

这样会把所有的新的api都加入编译后的代码,会显得很臃肿;

方法二

安装依赖:

yarn add -D @babel/polyfill

yarn add -D @babel/core

yarn add -D core-js

yarn add -D @babel/runtime

yarn add -D @babel/preset-env

yarn add -D @babel/plugin-transform-runtime

yarn add -D @babel/runtime-corejs3

配置根目录.babelrc:文件:

{
    "plugins": [
        [
        "@babel/plugin-transform-runtime",
            {
            "regenerator": false,
            "useESModules": true,
            "corejs": 3
            }
        ],
        // ["@babel/plugin-proposal-decorators", { "legacy": true }], // 装饰器
        // ["@babel/plugin-proposal-class-properties", { "loose": true }] //箭头函数
    ],
    "presets": [
        [
        "@babel/preset-env",
            {
                "modules":false,
                "useBuiltIns": "usage",
                "corejs": 3,
                "targets": {
                    "browsers": ["last 2 versions", "ie >= 9"]
                }
            }
        ],
        // "@babel/preset-react" //转化react
    ]
}

注:注释对应的内容:

  • 支持装饰器还需要安装 @babel/plugin-proposal-decorators
  • 支持箭头函数需要安装 @babel/plugin-proposal-class-properties
  • 支持react需要安装 @babel/preset-react

方法三

主入口引入模块:

import 'babel-polyfill';

.babelrc:

{
    "plugins": [
        [
        "@babel/plugin-transform-runtime",
            {
            "regenerator": false,
            "useESModules": true,
            "corejs": 3
            }
        ],
        // ["@babel/plugin-proposal-decorators", { "legacy": true }], // 装饰器
        // ["@babel/plugin-proposal-class-properties", { "loose": true }] //箭头函数
    ],
    "presets": [
        [
        "@babel/preset-env",
            {
                "modules":false,
                "useBuiltIns": "entry",//这里和方法二不一样
                "corejs": 3,
                "targets": {
                    "browsers": ["last 2 versions", "ie >= 9"]
                }
            }
        ],
        // "@babel/preset-react" //转化react
    ]
}

关键点是useBuiltIns这一配置项,它的值有三种:

false: 不对polyfill做任何操作

entry: 根据target中浏览器版本的支持,将polyfill拆分引入,仅引入有浏览器不支持的polyfill

usage(新):检测代码中ES6/7/8等的使用情况,仅仅加载代码中用到的polyfill

参考:Show me the code,babel 7 最佳实践,https://juejin.im/post/5c03a4d0f265da615e053612

按需加载polyfill——babel7的正确打开方式

https://erasermeng.github.io/2017/11/02/%E6%8C%89%E9%9C%80%E5%8A%A0%E8%BD%BDpolyfill%E2%80%94%E2%80%94babel7%E7%9A%84%E6%AD%A3%E7%A1%AE%E6%89%93%E5%BC%80%E6%96%B9%E5%BC%8F/

xianzou avatar Jun 01 '19 07:06 xianzou