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


当前回答

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

其他回答

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/

我有使用webpack/babel构建的异步等待:

"devDependencies": {
    "babel-preset-stage-3": "^6.11.0"
}

babelrc语言:

"presets": ["es2015", "stage-3"]

Babel 7用户

我很难绕过这个问题,因为大多数信息都是以前的babel版本。对于Babel 7,安装以下两个依赖项:

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

在.babelrc中,添加:

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

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

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

安装再生器运行时:

npm i -D regenerator-runtime

然后在webpack配置中添加:

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

笔记如果您使用的是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
    }]
  ]
}