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


当前回答

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

npm安装babel polyfill

然后在所有其他脚本标记之上向index.html添加一个脚本标记,并引用node_modules中的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()

    ]
};

对于希望使用babel polyfill版本7^的用户,请使用webpack ver3^进行此操作。

Npm安装模块Npm i-D@babel/polyfill

然后在入口点的webpack文件中执行以下操作

entry: ['@babel/polyfill', path.resolve(APP_DIR, 'App.js')],

当我尝试使用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>

我正在使用React和Django项目,并通过使用再生器运行时使其工作。你应该这样做,因为@babel/polyfill会增加你的应用程序的大小,而且也被弃用。我还遵循本教程的第1集和第2集创建了我的项目结构。

*包.json*

...
"devDependencies": {
    "regenerator-runtime": "^0.13.3",
    ...
}

巴氏合金

{
   "presets": ["@babel/preset-env", "@babel/preset-react"],
   "plugins": ["transform-class-properties"]
}

索引js

...
import regeneratorRuntime from "regenerator-runtime";
import "regenerator-runtime/runtime";
ReactDOM.render(<App />, document.getElementById('app'));
...

我需要支持的目标浏览器已经支持异步/等待,但是在编写mocha测试时,如果没有正确的设置,我仍然会遇到这个错误。

我在谷歌上搜索的大多数文章都过时了,包括这里的公认答案和高投票率答案,即你不需要polyfill、babel再生器运行时、babel插件转换运行时。如果您的目标浏览器已经支持异步/等待(当然,如果您不需要polyfill)

我也不想使用webpack。

泰勒·龙的答案实际上是正确的,因为他建议babel预置env(但我先省略了它,因为他在开头提到了polifill)。我仍然得到了ReferenceError:regeneratorRuntime最初没有定义,然后我意识到这是因为我没有设置目标。为节点设置目标后,我修复了再生器运行时错误:

  "scripts": {
    //"test": "mocha --compilers js:babel-core/register"
    //https://github.com/mochajs/mocha/wiki/compilers-deprecation
    "test": "mocha --require babel-core/register"
  },
  "devDependencies": {
    "babel-core": "^6.26.3",
    "babel-preset-env": "^1.7.0",
    "mocha": "^5.2.0"
  },
  //better to set it .bablerc, I list it here for brevity and it works too.
  "babel": {
    "presets": [
      ["env",{
        "targets": {
          "node": "current"
           "chrome": 66,
           "firefox": 60,
        },
        "debug":true
      }]
    ]
  }