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


当前回答

我在Chrome中遇到了这个问题。与RieneVaPlu的回答类似,这为我解决了问题:

npm install --save-dev regenerator-runtime

然后在我的代码中:

import 'regenerator-runtime/runtime';

很高兴避免babel polyfill额外的200 kB。

其他回答

尝试将其添加到package.json中

"browserslist": [
  "last 2 Chrome versions"
]

这对我有用!

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

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

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

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

安装@babel polyfill并将其保存在开发依赖项中

npm安装--保存dev@babel/polyfill

复制和粘贴需要(“@babel/polyfill”);在输入文件的顶部

入口.js

require("@babel/polyfill"); // this should be include at the top

在条目数组中添加@babel/polyfill您需要在预设数组中预设env

webpack.config.js

常量路径=require('path');要求(“@babel/polyfill”);//必要的,必要的模块导出={条目:['@babel/polyfill','./src/js/index.js'],输出:{路径:路径.解析(__dirname,'to_be_deployed/js'),文件名:'main.js'},模块:{规则:[{测试:/\.m?js$/,exclude:/node_modules/,使用:{loader:“babel loader”,选项:{预设:['@babel/preset-env']}}}]},mode:'开发'}

新答案你为什么要听我的答案?

答:因为我将用最新的更新版本npm项目给你们一个答案。

04/14/2017

"name": "es6",
 "version": "1.0.0",
   "babel-core": "^6.24.1",
    "babel-loader": "^6.4.1",
    "babel-polyfill": "^6.23.0",
    "babel-preset-es2015": "^6.24.1",
    "webpack": "^2.3.3",
    "webpack-dev-server": "^2.4.2"

如果您使用此版本或更高版本的Npm和所有其他。。。所以只需要改变:

webpack.config.js

module.exports = {
  entry: ["babel-polyfill", "./app/js"]
};

更改webpack.config.js文件后,只需将这一行添加到代码顶部。

import "babel-polyfill";

现在检查一切是否正常。参考链接

也感谢@BrunoLM的回答。