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

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

其他回答

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

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

mocha --require babel-polyfill

这些答案中的大多数都推荐了使用WebPack处理此错误的解决方案。但如果有人在使用RollUp(就像我一样),以下是最终对我有效的方法(只需一个提示,将这个polyfill广告捆绑在一起,总输出大小约为10k):

巴氏合金

{
    "presets": [
        [
            "env",
            {
                "modules": false,
                "targets": {
                    "browsers": ["last 2 versions"]
                }
            }
        ]
    ],
    "plugins": ["external-helpers",
        [
            "transform-runtime",
            {
                "polyfill": false,
                "regenerator": true
            }
        ]]
}

汇总配置.js

import resolve from 'rollup-plugin-node-resolve';
import babel from 'rollup-plugin-babel';
import uglify from 'rollup-plugin-uglify';
import commonjs from 'rollup-plugin-commonjs';


export default {
    input: 'src/entry.js',
    output: {
        file: 'dist/bundle.js',
        format: 'umd',
        name: 'MyCoolLib',
        exports: 'named'
    },
    sourcemap: true,
    plugins: [
        commonjs({
            // polyfill async/await
            'node_modules/babel-runtime/helpers/asyncToGenerator.js': ['default']
        }),
        resolve(),
        babel({
            runtimeHelpers: true,
            exclude: 'node_modules/**', // only transpile our source code
        }),
        uglify()

    ]
};

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

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

小心吊装功能

我的“polyfill导入”和“异步函数”都在同一个文件中,但我使用的是将其提升到polyfill之上的函数语法,这会给我带来ReferenceError:regeneratorRuntime未定义错误。

更改此代码

import "babel-polyfill"
async function myFunc(){ }

到此为止

import "babel-polyfill"
var myFunc = async function(){}

以防止其悬挂在polyfill进口上方。

或者,如果您不需要babel polyfill提供的所有模块,您可以在webpack配置中指定babel再生器运行时:

module.exports = {
  entry: ['babel-regenerator-runtime', './test.js'],

  // ...
};

当将webpack-dev-server与HMR一起使用时,这样做可以大大减少每次构建时必须编译的文件数量。这个模块是作为babel polyfill的一部分安装的,所以如果你已经有了,你就可以了,否则你可以用npm i-D babel再生器运行时单独安装它。