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


当前回答

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 polyfill版本7^的用户,请使用webpack ver3^进行此操作。

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

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

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

安装babel polyfillnpm安装--保存@babel/polyfill更新webpack文件entry:[“@babel/polyfill”,“<your enter js file>”]

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

npm安装babel polyfill

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

我有使用webpack/babel构建的异步等待:

"devDependencies": {
    "babel-preset-stage-3": "^6.11.0"
}

babelrc语言:

"presets": ["es2015", "stage-3"]

我的工作babel 7样板,用于与再生器运行时反应:

巴氏合金

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "targets": {
          "node": true,
        },
      },
    ],
    "@babel/preset-react",
  ],
  "plugins": [
    "@babel/plugin-syntax-class-properties",
    "@babel/plugin-proposal-class-properties"
  ]
}

包.json

...

"devDependencies": {
  "@babel/core": "^7.0.0-0",
  "@babel/plugin-proposal-class-properties": "^7.4.4",
  "@babel/plugin-syntax-class-properties": "^7.2.0",
  "@babel/polyfill": "^7.4.4",
  "@babel/preset-env": "^7.4.5",
  "@babel/preset-react": "^7.0.0",
  "babel-eslint": "^10.0.1",
...

main.js

import "@babel/polyfill";

....