尽管拥有正确的预设/插件,但Babel会在async / await语法上抛出错误

时间:2016-10-05 17:01:04

标签: javascript async-await babeljs

我正在尝试使用Babel编译async / await函数,但我收到编译错误。

这是我的功能:

async function login(username, password) {
  try {
    const response = await request
      .post("/api/login")
      .set("Accept", "application/json")
      .send({username, password})
      .end();

    const {user} = response.body;
    console.log("Login success:", user);
    this.user = user;
    this.loginError = null;
  } catch(error) {
    console.log(`Login failed: ${error}`);
    this.user = null;
    this.loginError = error;
  }
}

这是错误:

ERROR in ./src/store/store.js
Module parse failed: /home/james/projects/Issue-Tracker/node_modules/babel-loader/index.js!/home/james/projects/Issue-Tracker/src/store/store.js The keyword 'await' is reserved (20:25)
You may need an appropriate loader to handle this file type.
SyntaxError: The keyword 'await' is reserved (20:25)
    at Parser.pp$4.raise (/home/james/projects/Issue-Tracker/node_modules/acorn/dist/acorn.js:2221:15)
    at Parser.pp$3.parseIdent (/home/james/projects/Issue-Tracker/node_modules/acorn/dist/acorn.js:2182:14)
    at Parser.pp$3.parseExprAtom (/home/james/projects/Issue-Tracker/node_modules/acorn/dist/acorn.js:1774:21)
    at Parser.pp$3.parseExprSubscripts (/home/james/projects/Issue-Tracker/node_modules/acorn/dist/acorn.js:1715:21)
    at Parser.pp$3.parseMaybeUnary (/home/james/projects/Issue-Tracker/node_modules/acorn/dist/acorn.js:1692:19)
    at Parser.pp$3.parseExprOps (/home/james/projects/Issue-Tracker/node_modules/acorn/dist/acorn.js:1637:21)
    at Parser.pp$3.parseMaybeConditional (/home/james/projects/Issue-Tracker/node_modules/acorn/dist/acorn.js:1620:21)
    at Parser.pp$3.parseMaybeAssign (/home/james/projects/Issue-Tracker/node_modules/acorn/dist/acorn.js:1597:21)
    at Parser.pp$3.parseMaybeAssign (/home/james/projects/Issue-Tracker/node_modules/acorn/dist/acorn.js:1608:25)
    at Parser.pp$3.parseExpression (/home/james/projects/Issue-Tracker/node_modules/acorn/dist/acorn.js:1573:21)
    at Parser.pp$1.parseStatement (/home/james/projects/Issue-Tracker/node_modules/acorn/dist/acorn.js:727:47)
    at Parser.pp$1.parseBlock (/home/james/projects/Issue-Tracker/node_modules/acorn/dist/acorn.js:981:25)
    at Parser.pp$1.parseTryStatement (/home/james/projects/Issue-Tracker/node_modules/acorn/dist/acorn.js:897:23)
    at Parser.pp$1.parseStatement (/home/james/projects/Issue-Tracker/node_modules/acorn/dist/acorn.js:702:31)
    at Parser.pp$1.parseSwitchStatement (/home/james/projects/Issue-Tracker/node_modules/acorn/dist/acorn.js:873:36)
    at Parser.pp$1.parseStatement (/home/james/projects/Issue-Tracker/node_modules/acorn/dist/acorn.js:700:34)
 @ ./src/store/index.js 7:13-31

这是我的.babelrc

{
  "presets": ["latest", "react"],
  "plugins": ["transform-decorators-legacy", "transform-object-rest-spread", "transform-class-properties"]
}

根据babel-preset-latest的文档,它包括preset-es2017,其中包括transform-async-to-generator,所以我不明白为什么这不会编译。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

的package.json

{
  "dependencies": {
    "babel-cli": "^6.18.0",
    "babel-plugin-transform-class-properties": "^6.18.0",
    "babel-plugin-transform-decorators-legacy": "^1.3.4",
    "babel-plugin-transform-object-rest-spread": "^6.16.0",
    "babel-preset-latest": "^6.16.0",
    "babel-preset-react": "^6.16.0"
  }
}

.babelrc

{
  "presets": ["latest", "react"],
  "plugins": [
    "transform-decorators-legacy",
    "transform-object-rest-spread",
    "transform-class-properties"
   ]
}

如果要构建的文件的名称为file.js,则为:

$ node_modules/.bin/babel file.js -o output.js

你应该有输出.js

"use strict";

var login = function () {
  var _ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee(username, password) {
    var response, user;
    return regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.prev = 0;
            _context.next = 3;
            return request.post("/api/login").set("Accept", "application/json").send({ username: username, password: password }).end();

          case 3:
            response = _context.sent;
            user = response.body.user;

            console.log("Login success:", user);
            this.user = user;
            this.loginError = null;
            _context.next = 15;
            break;

          case 10:
            _context.prev = 10;
            _context.t0 = _context["catch"](0);

            console.log("Login failed: " + _context.t0);
            this.user = null;
            this.loginError = _context.t0;

          case 15:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, this, [[0, 10]]);
  }));

  return function login(_x, _x2) {
    return _ref.apply(this, arguments);
  };
}();

function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }