我正在尝试在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 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:'开发'}

其他回答

我有一个设置使用预设的webpack:['es2015','stage-0']以及运行webpack编译的测试的mocha。

为了使测试中的异步/等待工作,我只需要使用mocha和--require-babel polyfill选项:

mocha --require babel-polyfill

至babel7用户和ParcelJS>=1.1.0用户

npm i @babel/runtime-corejs2
npm i --save-dev @babel/plugin-transform-runtime @babel/core

巴氏合金

{
  "plugins": [
    ["@babel/plugin-transform-runtime", {
      "corejs": 2
    }]
  ]
}

取自https://github.com/parcel-bundler/parcel/issues/1762

供将来参考:

从Babel版本7.0.0-beta.55起,已删除舞台预设

参考博客https://babeljs.io/blog/2018/07/27/removing-babels-stage-presets

异步等待仍然可以由

https://babeljs.io/docs/en/babel-plugin-transform-async-to-generator#usage

安装

npm install --save-dev @babel/plugin-transform-async-to-generator

babelrc中的用法

 { 
     "presets": ["@babel/preset-env"],
     "plugins": ["@babel/plugin-transform-async-to-generator"]
 }

并使用babel polyfillhttps://babeljs.io/docs/en/babel-polyfill

安装

npm install --save @babel/polyfill

webpack.config.js

module.exports = {
  entry: ["@babel/polyfill", "./app/js"],
};

1-安装babel插件,将异步转换为模块方法,babel polyfil,蓝鸟,babel-reset-es2015,babel芯:

npm install babel-plugin-transform-async-to-module-method babel-polyfill bluebird babel-preset-es2015 babel-core

2-添加js babel polyfill:

导入“babel polyfill”;

3-在.babelrc中添加插件:

{
    "presets": ["es2015"],
    "plugins": [
      ["transform-async-to-module-method", {
        "module": "bluebird",
        "method": "coroutine"
      }]
    ]
}

资料来源:http://babeljs.io/docs/plugins/transform-async-to-module-method/

我在Chrome中遇到了这个问题。与RieneVaPlu的回答类似,这为我解决了问题:

npm install --save-dev regenerator-runtime

然后在我的代码中:

import 'regenerator-runtime/runtime';

很高兴避免babel polyfill额外的200 kB。