我正在尝试在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的情况下正常使用它,效果很好。知道我做错了什么吗?


当前回答

只需安装再生器运行时具有以下命令

npm i regenerator-runtime

在需要服务器文件之前,在启动文件中添加以下行

require("regenerator-runtime/runtime");

到目前为止,这对我很有效

其他回答

当我尝试使用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>

只需安装再生器运行时具有以下命令

npm i regenerator-runtime

在需要服务器文件之前,在启动文件中添加以下行

require("regenerator-runtime/runtime");

到目前为止,这对我很有效

至babel7用户和ParcelJS>=1.1.0用户

npm i @babel/runtime-corejs2
npm i --save-dev @babel/plugin-transform-runtime @babel/core

巴氏合金

{
  "plugins": [
    ["@babel/plugin-transform-runtime", {
      "corejs": 2
    }]
  ]
}

取自https://github.com/parcel-bundler/parcel/issues/1762

截至2019年10月,这对我有效:

将其添加到预设中。

 "presets": [
      "@babel/preset-env"
    ]

然后使用npm安装再生器运行时。

npm i regenerator-runtime

然后在主文件中使用:(此导入仅使用一次)

import "regenerator-runtime/runtime";

这将使您能够在文件中使用异步等待并删除再生器错误

如果使用babel-preset-stage-2,则只需使用--requirebabelpolyfill启动脚本即可。

在我的案例中,这个错误是由Mocha测试引发的。

以下修复了问题

mocha\“server/tests/**/*.test.js\”--编译器js:babel寄存器--需要babel polyfill