我正在尝试在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

其他回答

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

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

mocha --require babel-polyfill

我使用了来自https://github.com/babel/babel/issues/9849#issuecomment-592668815,并将targets:{esmodules:true,}添加到我的babel.config.js。

module.exports = {
  presets: [
    [
      '@babel/preset-env',
      {
        targets: {
          esmodules: true,
        },
      },
    ],
  ],
}

在一个使用babel.buildExternalHelpers()和babel插件外部帮助程序创建自定义babelHelpers.js文件的场景中,我认为对客户端来说成本最低的解决方案是将再生器runtime/runtime.js添加到输出中,而不是添加所有polyfill。

// runtime.js
npm install --save regenerator-runtime

// building the custom babelHelper.js
fs.writeFile(
    './babelHelpers.js',
    fs.readFileSync('node_modules/regenerator-runtime/runtime.js')
    + '\n'
    + require('babel-core').buildExternalHelpers()
)

当包含babel polyfill时,此解决方案减少到约20KB,而不是约230KB。

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

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