Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
815 views
in Technique[技术] by (71.8m points)

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

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...