Babel ES7异步 - regeneratorRuntime未定义

13

我在我的项目中使用 browserify + gulp + babel,但是在使用 ES7 特性时遇到了问题。这是我安装的内容:

  • babel-plugin-transform-async-to-generator@6.8.0
  • babel-plugin-transform-decorators-legacy@1.3.4 // 用于使用装饰器
  • babel-polyfill@6.9.1
  • babel-preset-es2015@6.9.0
  • babel-preset-es2016@6.11.0
  • babel-preset-stage-0@6.5.0
  • babelify@7.3.0
  • browserify@13.0.1
  • gulp
  • gulp-sourcemaps
  • vinyl-buffer
  • vinyl-source-stream

这是我的 gulp 代码:

gulp.task('build', () => {
    let buildPath;
    let destPath;

    buildPath = `./src`;
    destPath = `./dist`;

    return browserify(`${buildPath}/app.js`)
    .transform(babelify, { 
        presets: ["es2015", "es2016", "stage-0"],
        plugins: ["transform-decorators-legacy", "transform-async-to-generator"]
    })
    .bundle()
    .pipe(source('app.js'))
    .pipe(buffer())
    .pipe(sourcemaps.init({loadMaps: true}))
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest(`${destPath}`));
});

以下是我的 JavaScript 代码:

import 'babel-polyfill';

// Async Functions
function wait(t) {
    return new Promise((r) => setTimeout(r, t));
}

async function asyncMania() {
    console.log('1');
    await wait(1000);
    console.log('2');
}

asyncMania().then(() => console.log('3'));

当我尝试时,出现了错误:
Uncaught ReferenceError: regeneratorRuntime未定义
使用require而不是import也不起作用。大多数问题都使用Webpack,而其他方法对我来说都没有起作用,所以如果您能告诉我应该怎么做,我将非常感激。
我还有一个问题,正如您所看到的,我安装了babel-preset-es2015和babel-preset-es2016,并且两者都在使用。如果我删除es2015插件,我还能使用ES6功能吗?此外,我包括babel-preset-stage-0,我知道这是用于实验性ES7功能。babel-preset-es2016实际上是什么?

我安装了transform-regenerator插件和transform-async-functions,但还是无法工作。:( - modernator
1个回答

4

我使用最新的babel + async插件 + babel-polyfill解决了这个问题。谢谢。 - modernator
太棒了!我甚至不需要babel-polyfill就能让它工作。 - Ranveer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接