我正在尝试在Babel 6上从头开始使用async/await,但我得到的是regeneratorRuntime没有定义。

.babelrc文件

{
    "presets": [ "es2015", "stage-0" ]
}

package.json文件

"devDependencies": {
    "babel-core": "^6.0.20",
    "babel-preset-es2015": "^6.0.15",
    "babel-preset-stage-0": "^6.0.15"
}

.js文件

"use strict";
async function foo() {
  await bar();
}
function bar() { }
exports.default = foo;

在没有async/await的情况下正常使用它,效果很好。知道我做错了什么吗?


当前回答

我正在使用React和Django项目,并通过使用再生器运行时使其工作。你应该这样做,因为@babel/polyfill会增加你的应用程序的大小,而且也被弃用。我还遵循本教程的第1集和第2集创建了我的项目结构。

*包.json*

...
"devDependencies": {
    "regenerator-runtime": "^0.13.3",
    ...
}

巴氏合金

{
   "presets": ["@babel/preset-env", "@babel/preset-react"],
   "plugins": ["transform-class-properties"]
}

索引js

...
import regeneratorRuntime from "regenerator-runtime";
import "regenerator-runtime/runtime";
ReactDOM.render(<App />, document.getElementById('app'));
...

其他回答

您会收到一个错误,因为async/await使用的生成器是ES2016特性,而不是ES2015。解决此问题的一种方法是为ES2016安装babel预设(npm install--save babel-preset-ES2016),并编译为ES2016而不是ES2015:

"presets": [
  "es2016",
  // etc...
]

正如其他答案所提到的,您也可以使用polyfill(尽管确保在运行任何其他代码之前先加载polyfill)。或者,如果不想包含所有polyfill依赖项,可以使用babel再生器运行时或babel插件转换运行时。

当我尝试使用ES6生成器时,使用gulf with rollup时会出现以下错误:

gulp.task('scripts', () => {
  return rollup({
    entry: './app/scripts/main.js',
    format: "iife",
    sourceMap: true,
    plugins: [babel({
      exclude: 'node_modules/**',
      "presets": [
        [
          "es2015-rollup"
        ]
      ],
      "plugins": [
        "external-helpers"
      ]
    }),
    includePaths({
      include: {},
      paths: ['./app/scripts'],
      external: [],
      extensions: ['.js']
    })]
  })

  .pipe(source('app.js'))
  .pipe(buffer())
  .pipe(sourcemaps.init({
    loadMaps: true
  }))
  .pipe(sourcemaps.write('.'))
  .pipe(gulp.dest('.tmp/scripts'))
  .pipe(reload({ stream: true }));
});

我可能认为解决方案是将babel polyfill作为bower组件:

bower install babel-polyfill --save

并将其作为依赖项添加到index.html中:

<script src="/bower_components/babel-polyfill/browser-polyfill.js"></script>

在控制台中修复此“regeneratorRuntime未定义问题”的最简单方法:

你不必安装任何不必要的插件。只需添加:

<script src=“https://unpkg.com/regenerator-runtime@0.13.1/runtime.js“></script>

在你的index.html中。现在,一旦您运行babel,就应该定义regeneratorRuntime,现在您的异步/等待函数应该成功编译到ES2015中

在2019年Babel 7.4.0+中,Babel polyfill包已被弃用,转而直接包含core js/stable(core-js@3+,到polyfill ECMAScript功能)和再生器运行时/运行时(需要使用转译生成器函数):

import "core-js/stable";
import "regenerator-runtime/runtime";

babel polyfill文档中的信息。

当在没有正确的Babel插件的情况下使用异步/等待函数时,会导致此错误。截至2020年3月,以下应该是您需要做的全部工作

在命令行中,键入:

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

在您的babel.config.js文件中,添加这个插件@babel/plugin-transform运行时。注意:下面的示例包括我最近为一个小型React/Node/Express项目所做的其他预设和插件:

module.exports = {
  presets: ['@babel/preset-react', '@babel/preset-env'],
  plugins: ['@babel/plugin-proposal-class-properties', 
  '@babel/plugin-transform-runtime'],
};