我正在尝试在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配置中指定babel再生器运行时:

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

  // ...
};

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

其他回答

在控制台中修复此“regeneratorRuntime未定义问题”的最简单方法:

你不必安装任何不必要的插件。只需添加:

<script src=“https://unpkg.com/regenerator-runtime@0.13.1/runtime.js“></script>

在你的index.html中。现在,一旦您运行babel,就应该定义regeneratorRuntime,现在您的异步/等待函数应该成功编译到ES2015中

在反应预设之前使用阶段2预设帮助我:

npx babel --watch src --out-dir . --presets stage-2,react

安装以下模块时,上述代码有效:

npm install babel-cli babel-core babel-preset-react babel-preset-stage-2 --save-dev

我使用了来自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 polyfill提供的所有模块,您可以在webpack配置中指定babel再生器运行时:

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

  // ...
};

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

我的工作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";

....