Best way to polyfill ES6 features in React app tha

2019-01-21 08:47发布

问题:

I've been testing my React.js application on internet explorer, and to my surprise, ES6 code like Array.prototype.includes() breaks it. I'm using the creat-react-app starter kit and I thought babel was a part of this, and that it allowed me to write ES6 code.

Turns out its not quite so simple. From what I can see, they've chosen NOT to include a lot of polyfill as not everyone needs it, and it slows down build times. See for example here and here. There has been an attempt to document this, but there is no mention of how to actually do the polyfills yourself. Just this:

If you use any other ES6+ features that need runtime support (such as Array.from() or Symbol), make sure you are including the appropriate polyfills manually, or that the browsers you are targeting already support them.

So... what is the best way to 'manually' include them? I thought that's part of what babel is for? Should I partially import elements of babel-polyfill?

回答1:

These two approaches both work:

1. Manual import from core-js (edited based on Dan's comment)

Create a file called (something like) polyfills.js and import it into root index.js file.

Run npm install core-js or yarn add core-js and import your specific required features, like so:

/* polyfills.js */

import 'core-js/fn/array/find';
import 'core-js/fn/array/includes';
import 'core-js/fn/number/is-nan';

2. Polyfill service

Use the polyfill.io CDN to retrieve custom, browser-specific polyfills by adding this line to index.html:

<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=default,Array.prototype.includes"></script>

note, I had to explicity request the Array.prototype.includes feature as it is not included in the default feature set.



回答2:

I used yarn to download the polyfill and imported it directly in my index.js.

In command prompt:

yarn add array.prototype.fill

And then, at the top of index.js:

import 'array.prototype.fill' // <-- newly added import
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
...

I like this approach since I am specifically importing what I need into the project.



回答3:

Use the react-app-polyfill which has polyfills for the common ES6 features used in React. And it's part of create-react-app. Make sure you include it at the start of index.js as defined in the README.



回答4:

Eject from your Create React App Project

Afterwards you can put all your polyfills in your /config/polyfills.js file

Put the following at the end of the file

Object.values = Object.values ? Object.values : o=>Object.keys(o).map(k=>o[k]);

Webpack will automatically fix this for you ;)