How do I install the babel-polyfill library?

后端 未结 7 1393
旧时难觅i
旧时难觅i 2020-12-02 06:13

I just started to use Babel to compile my ES6 javascript code into ES5. When I start to use Promises it looks like it\'s not working. The Babel website states support for pr

7条回答
  •  醉酒成梦
    2020-12-02 06:57

    For Babel version 7, if your are using @babel/preset-env, to include polyfill all you have to do is add a flag 'useBuiltIns' with the value of 'usage' in your babel configuration. There is no need to require or import polyfill at the entry point of your App.

    With this flag specified, babel@7 will optimize and only include the polyfills you needs.

    To use this flag, after installation:

    npm install --save-dev  @babel/core @babel/cli @babel/preset-env
    npm install --save @babel/polyfill
    

    Simply add the flag:

    useBuiltIns: "usage" 
    

    to your babel configuration file called "babel.config.js" (also new to Babel@7), under the "@babel/env" section:

    // file: babel.config.js
    
    module.exports = () => {
       const presets = [
          [
             "@babel/env", 
             { 
                 targets: { /* your targeted browser */ },
                 useBuiltIns: "usage"  // <-----------------*** add this
             }
          ]
       ];
    
       return { presets };
    };
    

    Reference:

    • usage#polyfill
    • babel-polyfill#usage-in-node-browserify-webpack
    • babel-preset-env#usebuiltins

    Update Aug 2019:

    With the release of Babel 7.4.0 (March 19, 2019) @babel/polyfill is deprecated. Instead of installing @babe/polyfill, you will install core-js:

    npm install --save core-js@3
    

    A new entry corejs is added to your babel.config.js

    // file: babel.config.js
    
    module.exports = () => {
       const presets = [
          [
             "@babel/env", 
             { 
                 targets: { /* your targeted browser */ },
                 useBuiltIns: "usage",
                 corejs: 3  // <----- specify version of corejs used
             }
          ]
       ];
    
       return { presets };
    };
    

    see example: https://github.com/ApolloTang/stackoverflow-eg--babel-v7.4.0-polyfill-w-core-v3

    Reference:

    • 7.4.0 Released: core-js 3, static private methods and partial application
    • core-js@3, babel and a look into the future

提交回复
热议问题