19 Babel Polyfill是什么

  • 什么是Polyfill? Polyfill是一种JavaScriptAPIPolyfill,用来模拟实现一些JavaScript的新特性,使得这些新特性能够在旧的浏览器中运行
  • core-js是一个标准库,提供了一些常用的API的Polyfill,比如PromiseSetMap
  • core-js不支持generator,所以需要regenerator-runtimePolyfillregenerator-runtime是一个generatorPolyfill
  • @babel/polyfillcore-jsregenerator-runtime的集合,能满足ES6ES7等新语法的Polyfill需求
  • @babel/polyfill会污染全局变量,所以不推荐使用。在Babel 7.4之后,@babel/polyfill被废弃了,推荐使用core-jsregenerator-runtimePolyfill

    // 代码中使用babel/polyfill
    // 配置按需引入babel-polyfill 这里不用手动导入
    import "@babel/polyfill"

@babel/polyfill按需引入

  • 一次引入文件较大
  • 只有一部分功能,无需全部引入
  • 配置按需引入
    // .babelrc
    
    {
        "presets": [
            [
                "@babel/preset-env", // 一堆plugins的集合,包含常用的plugins
                {
                    "useBuiltIns": "usage", // 按需引入babel-polyfill
                    "corejs": 3 // corejs版本3
                } 
            ]
        ],
        "plugins": [
            [
                "@babel/plugin-transform-runtime",
                {
                    "absoluteRuntime": false,
                    "corejs": 3,
                    "helpers": true,
                    "regenerator": true,
                    "useESModules": false
                }
            ]
        ]

@babel/polyfill的问题

  • 会污染全局环境,挂载到window上, 会影响其他库 window.Promise = function(){} 使用方使用会覆盖冲突 window.Promise = '123'
  • 如果做一个独立的系统则无碍,但是如果是做一个第三方库,就会有问题

小结

babel-polyfill现在已经被弃用

  • babel 7.4之后弃用babel-polyfill
  • 直接推荐使用core-jsregenerator
Last Updated:
Contributors: leeguooooo