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


当前回答

babel再生器运行时现在已被弃用,而应该使用再生器。

要将运行时生成器与webpack和babel v7一起使用,请执行以下操作:

安装再生器运行时:

npm i -D regenerator-runtime

然后在webpack配置中添加:

entry: [
  'regenerator-runtime/runtime',
  YOUR_APP_ENTRY
]

其他回答

导入'babel polyfill'

其中使用异步等待

您会收到一个错误,因为async/await使用的生成器是ES2016特性,而不是ES2015。解决此问题的一种方法是为ES2016安装babel预设(npm install--save babel-preset-ES2016),并编译为ES2016而不是ES2015:

"presets": [
  "es2016",
  // etc...
]

正如其他答案所提到的,您也可以使用polyfill(尽管确保在运行任何其他代码之前先加载polyfill)。或者,如果不想包含所有polyfill依赖项,可以使用babel再生器运行时或babel插件转换运行时。

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

npm安装babel polyfill

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

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

上面有这么多答案,我会把我的答案贴出来供参考。我使用webpack并做出反应,这是我没有.babelrc文件的解决方案

我将于2020年8月对此进行研究

安装react和babel

npm i @babel/core babel-loader @babel/preset-env @babel/preset-react react react-dom @babel/plugin-transform-runtime --save-dev

然后在我的webpack.config.js中

// other stuff
module.exports = {
// other stuff

   module: {
   rules: [
  
   {
    test: /\.m?js$/,
    exclude: /(node_modules|bower_components)/,
    use: {
      loader: 'babel-loader',
      options: {
        presets: ['@babel/preset-env',"@babel/preset-react"],
        plugins: ['@babel/plugin-proposal-class-properties', '@babel/plugin-transform-runtime'],
        //npm install --save-dev @babel/plugin-transform-runtime
          }
        }
      },
    ],
  },

};

我只是不知道为什么我现在不需要安装异步包