Babel 6 regeneratorRuntime is not defined

前端 未结 30 1860
暖寄归人
暖寄归人 2020-11-22 03:49

I\'m trying to use async, await from scratch on Babel 6, but I\'m getting regeneratorRuntime is not defined.

.babelrc file

{
    \"presets\": [ \"es2         


        
30条回答
  •  长情又很酷
    2020-11-22 04:28

    Update: The Babel 7 post also has a more in-depth answer.


    Babel 7.4.0 or later (core-js 2 / 3)

    As of Babel 7.4.0, @babel/polyfill is deprecated.

    In general, there are two ways to install polyfills/regenerator: via global namespace (Option 1) or as ponyfill (Option 2, without global pollution).


    Option 1: @babel/preset-env

    presets: [
      ["@babel/preset-env", {
        "useBuiltIns": "usage",
        "corejs": 3, // or 2,
        "targets": {
            "firefox": "64", // or whatever target to choose .    
        },
      }]
    ]
    

    will automatically use regenerator-runtime and core-js according to your target. No need to import anything manually. Don't forget to install runtime dependencies:

    npm i --save regenerator-runtime core-js
    

    Alternatively, set useBuiltIns: "entry" and import it manually:

    import "regenerator-runtime/runtime";
    import "core-js/stable"; // if polyfills are also needed
    

    Option 2: @babel/transform-runtime with @babel/runtime

    This alternative has no global scope pollution and is suitable for libraries.

    {
      "plugins": [
        [
          "@babel/plugin-transform-runtime",
          {
            "regenerator": true,
            "corejs": 3 // or 2; if polyfills needed
            ...
          }
        ]
      ]
    }
    
    Install it:
    npm i -D @babel/plugin-transform-runtime
    npm i @babel/runtime
    

    If corejs polyfill is used, you replace @babel/runtime with @babel/runtime-corejs2 (for "corejs": 2) or @babel/runtime-corejs3 (for "corejs": 3).

提交回复
热议问题