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

    ]
};

其他回答

更新:Babel 7的帖子也有更深入的答案。


Babel 7.4.0或更高版本(核心js 2/3)

从Babel 7.4.0开始,@Babel/polyfill已弃用。

通常,有两种方法安装polyfills/reduator:通过全局命名空间(选项1)或作为ponyfill(选项2,无全局污染)。


选项1:@babel/preset-env

presets: [
  ["@babel/preset-env", {
    "useBuiltIns": "usage",
    "corejs": 3, // or 2,
    "targets": {
        "firefox": "64", // or whatever target to choose .    
    },
  }]
]

将根据您的目标自动使用再生器运行时和核心js。无需手动导入任何内容。不要忘记安装运行时依赖项:

npm i --save regenerator-runtime core-js

或者,设置useBuiltIns:“entry”并手动导入:

import "regenerator-runtime/runtime";
import "core-js/stable"; // if polyfills are also needed

选项2:@babel/transform runtime和@babel/runtime

这种替代方案没有全球范围的污染,适用于图书馆。

{
  "plugins": [
    [
      "@babel/plugin-transform-runtime",
      {
        "regenerator": true,
        "corejs": 3 // or 2; if polyfills needed
        ...
      }
    ]
  ]
}
Install it:
npm i -D @babel/plugin-transform-runtime
npm i @babel/runtime

如果使用了corejs polyfill,则将@babel/runtime替换为@babel/runtime-corejs2(对于“corejs”:2)或@babel/runtime-corejs3(对于“corejs”:3)。

当我尝试使用ES6生成器时,使用gulf with rollup时会出现以下错误:

gulp.task('scripts', () => {
  return rollup({
    entry: './app/scripts/main.js',
    format: "iife",
    sourceMap: true,
    plugins: [babel({
      exclude: 'node_modules/**',
      "presets": [
        [
          "es2015-rollup"
        ]
      ],
      "plugins": [
        "external-helpers"
      ]
    }),
    includePaths({
      include: {},
      paths: ['./app/scripts'],
      external: [],
      extensions: ['.js']
    })]
  })

  .pipe(source('app.js'))
  .pipe(buffer())
  .pipe(sourcemaps.init({
    loadMaps: true
  }))
  .pipe(sourcemaps.write('.'))
  .pipe(gulp.dest('.tmp/scripts'))
  .pipe(reload({ stream: true }));
});

我可能认为解决方案是将babel polyfill作为bower组件:

bower install babel-polyfill --save

并将其作为依赖项添加到index.html中:

<script src="/bower_components/babel-polyfill/browser-polyfill.js"></script>

我在尝试运行Mocha+Babel时遇到了这个问题。我有一个.babelrc在开发中运行(请参阅这里的其他答案,它们很完整),但我的npm运行测试命令仍然在抱怨regeneratorRuntime没有定义。所以我修改了package.json:

"scripts": {
  "test": "mocha --require babel-polyfill --require babel-core/register tests/*.js"
}

阅读更多信息:https://babeljs.io/en/setup/#mocha-4

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

npm安装babel polyfill

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

我在将项目转换为typescript项目后开始出现此错误。据我所知,问题源于异步/等待未被识别。

对我来说,通过在我的设置中添加两项内容,错误得到了修复:

正如上面多次提到的,我需要将babel polyfill添加到我的webpack条目数组中:...条目:['abel-polyfill','./index.js'],...我需要更新我的.babelrc,以允许将异步/等待编译为生成器:{“预设”:[“es2015”],“插件”:[“将异步转换为生成器”]}

开发依赖项:

我还必须在package.json文件中的devDependencies中安装一些东西。也就是说,我错过了babel插件将异步转换为生成器、babel polyfill和babel-preset-es2015:

 "devDependencies": {
    "babel-loader": "^6.2.2",
    "babel-plugin-transform-async-to-generator": "^6.5.0",
    "babel-polyfill": "^6.5.0",
    "babel-preset-es2015": "^6.5.0",
    "webpack": "^1.12.13"
 }

完整代码提示:

我从一个非常有用和简洁的GitHub要点中得到了代码,你可以在这里找到。