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


当前回答

上面有这么多答案,我会把我的答案贴出来供参考。我使用webpack并做出反应,这是我没有.babelrc文件的解决方案

我将于2020年8月对此进行研究

安装react和babel

npm i @babel/core babel-loader @babel/preset-env @babel/preset-react react react-dom @babel/plugin-transform-runtime --save-dev

然后在我的webpack.config.js中

// other stuff
module.exports = {
// other stuff

   module: {
   rules: [
  
   {
    test: /\.m?js$/,
    exclude: /(node_modules|bower_components)/,
    use: {
      loader: 'babel-loader',
      options: {
        presets: ['@babel/preset-env',"@babel/preset-react"],
        plugins: ['@babel/plugin-proposal-class-properties', '@babel/plugin-transform-runtime'],
        //npm install --save-dev @babel/plugin-transform-runtime
          }
        }
      },
    ],
  },

};

我只是不知道为什么我现在不需要安装异步包

其他回答

或者,如果您不需要babel polyfill提供的所有模块,您可以在webpack配置中指定babel再生器运行时:

module.exports = {
  entry: ['babel-regenerator-runtime', './test.js'],

  // ...
};

当将webpack-dev-server与HMR一起使用时,这样做可以大大减少每次构建时必须编译的文件数量。这个模块是作为babel polyfill的一部分安装的,所以如果你已经有了,你就可以了,否则你可以用npm i-D babel再生器运行时单独安装它。

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

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

babelrc语言:

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

只需安装再生器运行时具有以下命令

npm i regenerator-runtime

在需要服务器文件之前,在启动文件中添加以下行

require("regenerator-runtime/runtime");

到目前为止,这对我很有效

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'

其中使用异步等待