Babel - regeneratorRuntime is not defined, when using transform-async-to-generator plugin

雨燕双飞 提交于 2019-12-23 07:29:44

问题


I am not able to setup babel correctly for the usage of async / await.

I am using babel 7 and webpack 4.

I do not want to use babel-polyfill if possible!

My babelrc file:

{
    "presets": [[
        "@babel/env",
        {"modules": false}
    ]],
    "plugins": [
      "syntax-dynamic-import",
      "transform-async-to-generator"
    ]
}

Code:

async function init() {
  const loaderData = await initLoader();
  initCmp(loaderData)
    .then(initApi(loaderData.key))
    .catch();
}
init();

And Error:

refactor.main.js:18 Uncaught ReferenceError: regeneratorRuntime is not defined
    at eval (refactor.main.js:18)
    at eval (refactor.main.js:47)
    at Object../client/refactor.main.js (cmp.bundle.js:312)
    at __webpack_require__ (cmp.bundle.js:62)
    at eval (main.js:6)
    at Object../client/main.js (cmp.bundle.js:300)
    at __webpack_require__ (cmp.bundle.js:62)
    at cmp.bundle.js:179
    at cmp.bundle.js:182

回答1:


The latest documentation here is pretty clear: https://babeljs.io/docs/en/next/babel-plugin-transform-runtime

What worked for me is installing the two packages for build and for runtime (the final script for the browser):

npm install --save-dev @babel/plugin-transform-runtime

npm install --save @babel/runtime

In the plugin Array of my webpack configuration I just added '@babel/plugin-transform-runtime' without any options. (Please also have a look at the documentation linked above, since some options (that you might find in older tutorials or answers) have been removed.)

plugins: [
'@babel/plugin-transform-runtime'
]

I now can use async functions without errors, and it didn't add much code in the production build.




回答2:


You also need the transform-runtime plugin, so your .babelrc should ready:

{
    "presets": [[
        "@babel/env",
        {"modules": false}
    ]],
    "plugins": [
      "syntax-dynamic-import",
      "transform-runtime",
      "transform-async-to-generator"
    ]
}

Note that you'll also need to npm install --save-dev transform-runtime



来源:https://stackoverflow.com/questions/50907975/babel-regeneratorruntime-is-not-defined-when-using-transform-async-to-generat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!