javascriptreactjsecmascript-6create-react-appecmascript-2016

Best way to polyfill ES6 features in React app that uses create-react-app


I've been testing my React.js application on internet explorer, and finding that some ES6/7 code like Array.prototype.includes() breaks it.

I'm using create-react-app, and apparently they've chosen not to include a lot of polyfills since not everyone needs them, and they slow down build times (see for example here and here). The documentation (at time of writing) suggests:

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?


Solution

  • Update: The create-react-app polyfill approach and docs have changed since this question/answer. You should now include react-app-polyfill (here) if you want to support older browsers like ie11. However, this only includes the "...minimum requirements and commonly used language features", so you'll still want to use one of the approaches below for less common ES6/7 features (like Array.includes)


    These two approaches both work:


    1. Manual imports from react-app-polyfill and core-js

    Install react-app-polyfill and core-js (3.0+):

    npm install react-app-polyfill core-js or yarn add react-app-polyfill core-js

    Create a file called (something like) polyfills.js and import it into your root index.js file. Then import the basic react-app polyfills, plus any specific required features, like so:

    polyfills.js

    import 'react-app-polyfill/ie11';
    import 'core-js/features/array/find';
    import 'core-js/features/array/includes';
    import 'core-js/features/number/is-nan';
    

    index.js

    import './polyfills'
    
    ...etc...
    

    2. Polyfill service

    No longer advised. See this article