个性化阅读
专注于IT技术分析

javascript项目使用async报错:regeneratorRuntime is not defined

前端JS项目中使用Babel6编译,其中项目中使用了async和await,编译报错:regeneratorRuntime is not defined。其中.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;

问题分析和解答

Babel-polyfill是必须的,你必须按照babel-polyfill以支持async和await的使用,安装如下:

npm i -D babel-core babel-polyfill babel-preset-es2015 babel-preset-stage-0 babel-loader

package.json文件配置:

"devDependencies": {
  "babel-core": "^6.0.20",
  "babel-polyfill": "^6.0.16",
  "babel-preset-es2015": "^6.0.15",
  "babel-preset-stage-0": "^6.0.15"
}

.babelrc文件配置:

{
  "presets": [ "es2015", "stage-0" ]
}

使用async和await的js代码:

"use strict";

export default async function foo() {
  var s = await bar();
  console.log(s);
}

function bar() {
  return "bar";
}

在启动文件中添加:

require("babel-core/register");
require("babel-polyfill");

如果你使用webpack,你需要将它作为entry数组的第一个值添加到webpack配置文件中(一般是webpack.config.js),如下:

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

  output: {
    filename: 'bundle.js'       
  },

  module: {
    loaders: [
      { test: /\.jsx?$/, loader: 'babel', }
    ]
  }
};

如果你想要使用babel执行测试,可以这样使用:

mocha --compilers js:babel-core/register --require babel-polyfill
赞(0)
未经允许不得转载:srcmini » javascript项目使用async报错:regeneratorRuntime is not defined

评论 抢沙发

评论前必须登录!