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


当前回答

在控制台中修复此“regeneratorRuntime未定义问题”的最简单方法:

你不必安装任何不必要的插件。只需添加:

<script src=“https://unpkg.com/regenerator-runtime@0.13.1/runtime.js“></script>

在你的index.html中。现在,一旦您运行babel,就应该定义regeneratorRuntime,现在您的异步/等待函数应该成功编译到ES2015中

其他回答

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处理此错误的解决方案。但如果有人在使用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()

    ]
};

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 polyfillnpm安装--保存@babel/polyfill更新webpack文件entry:[“@babel/polyfill”,“<your enter js file>”]

在反应预设之前使用阶段2预设帮助我:

npx babel --watch src --out-dir . --presets stage-2,react

安装以下模块时,上述代码有效:

npm install babel-cli babel-core babel-preset-react babel-preset-stage-2 --save-dev