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

    ]
};

其他回答

此解决方案已过时。

我在这个视频的youtube评论中找到了解决方案https://www.youtube.com/watch?v=iWUR04B42Hc&lc=Ugyq8UJq-OyOzsKIIrB4AaABAg公司

这应该指向正确的注释。“贝丝w”找到了解决方案。

Beth W 3个月前(编辑)我在2019年不得不做的另一个改变是,babel显然不再使用v7之前的阶段0预设,所以在26:15时,我不得不做的不是“npm install--save dev babel polyfill babel-preset-stage-0”,而是:npm安装--保存@babel/polyfill这包括两个旧选项。然后,在应用程序的入口点中,我>包含了“@babel/polyfill”,并在查询预设中保持原样。因此,webpack配置最终看起来像:

const path = require('path');
module.exports = {
    entry: {
        app: ['@babel/polyfill', './src/app.js']
    },
    output: {
        path: path.resolve(__dirname, 'build'),
        filename: 'app.bundle.js'
    },
    mode: 'development',
    module: {
        rules: [{
            test: /\.js?$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
            query: {
                presets: ['@babel/preset-env']
            }
        }]
    }
}

希望这对某人有所帮助!

我使用了来自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 polyfill并将其保存在开发依赖项中

npm安装--保存dev@babel/polyfill

复制和粘贴需要(“@babel/polyfill”);在输入文件的顶部

入口.js

require("@babel/polyfill"); // this should be include at the top

在条目数组中添加@babel/polyfill您需要在预设数组中预设env

webpack.config.js

常量路径=require('path');要求(“@babel/polyfill”);//必要的,必要的模块导出={条目:['@babel/polyfill','./src/js/index.js'],输出:{路径:路径.解析(__dirname,'to_be_deployed/js'),文件名:'main.js'},模块:{规则:[{测试:/\.m?js$/,exclude:/node_modules/,使用:{loader:“babel loader”,选项:{预设:['@babel/preset-env']}}}]},mode:'开发'}

需要babel polyfill(自babel 7.4起已弃用)。您还必须安装它才能使异步/等待工作。

npm i -D babel-core babel-polyfill babel-preset-es2015 babel-preset-stage-0 babel-loader

包.json

"devDependencies": {
  "babel-core": "^6.0.20",
  "babel-polyfill": "^6.0.16",
  "babel-preset-es2015": "^6.0.15",
  "babel-preset-stage-0": "^6.0.15"
}

巴氏合金

{
  "presets": [ "es2015", "stage-0" ]
}

js与async/await(示例代码)

"use strict";

export default async function foo() {
  var s = await bar();
  console.log(s);
}

function bar() {
  return "bar";
}

在启动文件中

require("babel-core/register");
require("babel-polyfill");

如果您正在使用webpack,则需要将其作为webpack配置文件(通常为webpack.config.js)中条目数组的第一个值,如@Cemen注释所示:

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

  output: {
    filename: 'bundle.js'       
  },

  module: {
    loaders: [
      { test: /\.jsx?$/, loader: 'babel', }
    ]
  }
};

如果要使用babel运行测试,请使用:

mocha --compilers js:babel-core/register --require babel-polyfill

如果您使用Gulp+Babel作为前端,则需要使用Babel polyfill

npm安装babel polyfill

然后在所有其他脚本标记之上向index.html添加一个脚本标记,并引用node_modules中的babel polyfill