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

其中使用异步等待

其他回答

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

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

mocha --require babel-polyfill

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/

Babel 7用户

我很难绕过这个问题,因为大多数信息都是以前的babel版本。对于Babel 7,安装以下两个依赖项:

npm install --save @babel/runtime 
npm install --save-dev @babel/plugin-transform-runtime

在.babelrc中,添加:

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

当在没有正确的Babel插件的情况下使用异步/等待函数时,会导致此错误。截至2020年3月,以下应该是您需要做的全部工作

在命令行中,键入:

npm install --save-dev @babel/plugin-transform-runtime

在您的babel.config.js文件中,添加这个插件@babel/plugin-transform运行时。注意:下面的示例包括我最近为一个小型React/Node/Express项目所做的其他预设和插件:

module.exports = {
  presets: ['@babel/preset-react', '@babel/preset-env'],
  plugins: ['@babel/plugin-proposal-class-properties', 
  '@babel/plugin-transform-runtime'],
};

我正在使用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'));
...