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


当前回答

我有一个设置使用预设的webpack:['es2015','stage-0']以及运行webpack编译的测试的mocha。

为了使测试中的异步/等待工作,我只需要使用mocha和--require-babel polyfill选项:

mocha --require babel-polyfill

其他回答

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

我通过安装babel polyfill修复了这个错误

npm install babel-polyfill --save

然后我将其导入应用程序入口点

import http from 'http';
import config from 'dotenv';
import 'babel-polyfill';
import { register } from 'babel-core';
import app from '../app';

对于我包含的测试,需要在测试脚本中使用babel polyfill

"test": "export NODE_ENV=test|| SET NODE_ENV=test&& mocha --compilers 
  js:babel-core/register --require babel-polyfill server/test/**.js --exit"

笔记如果您使用的是babel7,则该包已重命名为@babel/plugin-transform runtime。

除了polyfill,我还使用babel插件转换运行时。插件描述如下:

外部化对助手和内置程序的引用,自动聚合填充代码而不会污染全局。这到底意味着什么?基本上,您可以使用Promise、Set、Symbol等内置功能,也可以无缝使用所有需要polyfill的Babel功能,而不会造成全局污染,因此非常适合于库。

它还支持异步/等待以及ES6的其他内置功能。

$ npm install --save-dev babel-plugin-transform-runtime

在.babelrc中,添加运行时插件

{
  "plugins": [
    ["transform-runtime", {
      "regenerator": true
    }]
  ]
}

1-安装babel插件,将异步转换为模块方法,babel polyfil,蓝鸟,babel-reset-es2015,babel芯:

npm install babel-plugin-transform-async-to-module-method babel-polyfill bluebird babel-preset-es2015 babel-core

2-添加js babel polyfill:

导入“babel polyfill”;

3-在.babelrc中添加插件:

{
    "presets": ["es2015"],
    "plugins": [
      ["transform-async-to-module-method", {
        "module": "bluebird",
        "method": "coroutine"
      }]
    ]
}

资料来源:http://babeljs.io/docs/plugins/transform-async-to-module-method/

babel再生器运行时现在已被弃用,而应该使用再生器。

要将运行时生成器与webpack和babel v7一起使用,请执行以下操作:

安装再生器运行时:

npm i -D regenerator-runtime

然后在webpack配置中添加:

entry: [
  'regenerator-runtime/runtime',
  YOUR_APP_ENTRY
]