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


当前回答

我的简单解决方案:

npm install --save-dev babel-plugin-transform-runtime
npm install --save-dev babel-plugin-transform-async-to-generator

巴氏合金

{
  "presets": [
    ["latest", {
      "es2015": {
        "loose": true
      }
    }],
    "react",
    "stage-0"
  ],
  "plugins": [
    "transform-runtime",
    "transform-async-to-generator"
  ]
}

其他回答

我使用了来自https://github.com/babel/babel/issues/9849#issuecomment-592668815,并将targets:{esmodules:true,}添加到我的babel.config.js。

module.exports = {
  presets: [
    [
      '@babel/preset-env',
      {
        targets: {
          esmodules: true,
        },
      },
    ],
  ],
}

当在没有正确的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'],
};

小心吊装功能

我的“polyfill导入”和“异步函数”都在同一个文件中,但我使用的是将其提升到polyfill之上的函数语法,这会给我带来ReferenceError:regeneratorRuntime未定义错误。

更改此代码

import "babel-polyfill"
async function myFunc(){ }

到此为止

import "babel-polyfill"
var myFunc = async function(){}

以防止其悬挂在polyfill进口上方。

安装@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:'开发'}

如果使用babel-preset-stage-2,则只需使用--requirebabelpolyfill启动脚本即可。

在我的案例中,这个错误是由Mocha测试引发的。

以下修复了问题

mocha\“server/tests/**/*.test.js\”--编译器js:babel寄存器--需要babel polyfill