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


当前回答

至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

其他回答

这些答案中的大多数都推荐了使用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()

    ]
};

在2019年Babel 7.4.0+中,Babel polyfill包已被弃用,转而直接包含core js/stable(core-js@3+,到polyfill ECMAScript功能)和再生器运行时/运行时(需要使用转译生成器函数):

import "core-js/stable";
import "regenerator-runtime/runtime";

babel polyfill文档中的信息。

导入'babel polyfill'

其中使用异步等待

小心吊装功能

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

更改此代码

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

到此为止

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

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

在一个使用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。