软件技术学习笔记

个人博客,记录软件技术与程序员的点点滴滴。

React Polyfill ReplaceAll

最近使用Create React App创建一个APP,使用react-app-polyfill/stable完成Polyfill,但是,发现string.replaceAll()函数一直没有polyfill。打开core-js/stable/index.js,发现已经包含了require('../modules/es.string.replace-all')。第一次遇到这种情况,相对懵逼。

经过一番的查阅,最后在babel官网看到一条消息(https://babeljs.io/docs/en/babel-preset-env#corejs):

By default, only polyfills for stable ECMAScript features are injected: if you want to polyfill proposals, you have three different options:

* when using useBuiltIns: "entry", you can directly import a proposal polyfill: import "core-js/proposals/string-replace-all".

原来是@babel/preset-env搞得鬼,默认不会加载core-js中stage-1/2/3/4的特性。使用CRA时,core-js默认配置就是entry,需要我们在自己的代码中显示引入stage-1/2/3/4。 改成如下即可:

import 'react-app-polyfill/stable';
import 'core-js/stage/4'

更加规范的话,自己项目中import core-js:

import 'core-js/stable';
import 'core-js/stage/4'
import 'regenerator-runtime/runtime';