当前位置: 代码迷 >> 综合 >> babel-polyfill与babel-plugin-transform-runtime
  详细解决方案

babel-polyfill与babel-plugin-transform-runtime

热度:75   发布时间:2023-12-12 06:08:09.0

babel-polyfill

babel-polyfill在应用中会模拟一个es2015+的环境,所以使用了babel-polyfill后可以使用内置对象如Promise和WeakMap,静态方法如Array.from和Object.assign,实例方法如Array.prototype.includes,以及generator函数(需要提供babel-plugin-transform-regenerator插件)。总的来说,polyfill修改了全局作用域,浏览器下是window,node下是global。

babel-polyfill主要由两部分组成,core-js和regenerator runtime。

core-js:提供了如ES5、ES6、ES7等规范中 中新定义的各种对象、方法的模拟实现。
regenerator:提供generator支持,如果应用代码中用到generator、async函数的话用到。

引入babel-polyfill全量包后文件会变得非常大。

babel-plugin-transform-runtime

babel-plugin-transform-runtime主要做了一下三件事:

  1. 当你使用 generators/async 函数时,自动引入 babel-runtime/regenerator (使用 regenerator 运行时而不会污染当前环境) 。
  2. 自动引入 babel-runtime/core-js 并映射 ES6 静态方法和内置插件(实现polyfill的功能且无全局污染,但是实例方法无法正常使用,如 “foobar”.includes(“foo”) )。
  3. 移除内联的 Babel helper 并使用模块 babel-runtime/helpers 代替(提取babel转换语法的代码)。
{"plugins": [["transform-runtime", {"helpers": true, // default"polyfill": true, // default"regenerator": true, // defalut"moduleName": "babel-runtime" // default}]]
}

不需要额外的配置就是使用默认配置,这样就可以。所以babel-plugin-transform-runtime不会污染全局环境,一般用在webpack打包的node中。正是因为此,transform-runtime被广泛用于第三方库中。

安装babel-plugin-transform-runtime回默认安装babel-runtime(所有的帮助函数都在这个包中)。

参考:

https://babeljs.io/docs/en/babel-plugin-transform-runtime
https://babeljs.io/docs/en/babel-plugin-transform-runtime#technical-details

https://www.cnblogs.com/chyingp/archive/2018/06/01/understanding-babel-polyfill.html
https://www.cnblogs.com/JRliu/p/8280055.html

  相关解决方案