Babel continues to encounter issues with async/await syntax, even with all the necessary presets and plugins installed

I am encountering a compiler error while attempting to compile an async/await function using Babel.

Below is the function in question:

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;
  }
}

The error message received is as follows:

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)
    ... (remaining error log omitted for brevity)

Additionally, here is my .babelrc configuration:

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

Although the documentation for babel-preset-latest suggests that it should handle transform-async-to-generator with preset-es2017, I am still facing compilation issues. Any insights or assistance on resolving this problem would be highly appreciated.

Answer №1

Dependencies in 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"
  }
}

Babel Configuration in .babelrc

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

If you want to build a file named file.js using Babel, run the following command:

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

The contents of output.js will be:

"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"); }); }; }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Maximizing the potential of selectors in jquery.min.js

Can anyone explain what the purpose of selectors = {cacheLength: is in the jquery.min.js file? Additionally, I'd like to know if it is feasible to modify the value of cacheLength using jQuery. =ga.getText=function(a){var b,c="",d=0,f=a.nodeT ...

Passing arguments from the command line to an npm script

The scripts section in my package.json is currently set up as follows: "scripts": { "start": "node ./script.js server" } This allows me to use npm start command to initiate the server. All working well so far. However, I ...

Achieving peak efficiency: Comparing the execution of actions through dispatching versus passing them as props

I have a technical query. I'm attempting to send a value from a child component to the store by utilizing an action dispatcher inside the child component. This action dispatcher then modifies the state value in the reducer. Would it be wise to pass v ...

The next/font feature functions perfectly in all areas except for a single specific component

New Experience with Next.js and Tailwind CSS Exploring the next/font Package Delving into the realm of the new next/font package has been quite interesting. Following the tutorial provided by Next.js made the setup process smooth sailing. I've incorp ...

Update your Electron application with the npm update command

I have recently published an app on a local npm repository, and this particular app serves as a crucial dependency for my second electron application. The electron app I am working on is structured around node_modules/my-first-app/dist/index.html. I am w ...

A guide to setting a custom icon for the DatePicker component in Material-UI 5

Seeking to incorporate custom Icons from react-feathers, I have implemented a CustomIcon component which returns the desired icon based on the name prop. Below is the code for this component. import React from 'react'; import * as Icon from &apo ...

Encountering a parser error during an Ajax request

Attempting to develop a login system with PHP, jQuery, Ajax, and JSON. It successfully validates empty fields, but upon form submission, the Ajax call fails. The response text displays a JSON array in the console, indicating that the PHP part is not the is ...

What is the reason for the reconnect function not activating when manually reconnecting in Socket.IO?

After disconnecting the client from the node server using socket.disconnect(true);, I manually re-establish the connection on the client side with socket.open(). The issue arises when triggering socket.open(); the socket.on('reconnect', (attempt ...

Concealing certain elements within a loop using a "show more" button

In my PHP code, I am utilizing a foreach loop in the following manner: <div class="items"> @foreach($results as $details) <div class="col s2 l2"> {{ $details }} </div></div> My approach involves using the blade templating feature ...

Use jQuery Ajax to fetch an image and display it on the webpage

Currently, I am working on an application that is designed to browse through a large collection of images. The initial phase of the project involved sorting, filtering, and loading the correct images, as well as separating them into different pages for imp ...

Steps to retrieve the value of a particular row in a table using vuejs

Can you help me retrieve the value of a specific row in a table using VueJS 2? Here is an image of my current table: I need assistance with obtaining and displaying the last value from a loop in the "SHOW QR Button" within my code snippet. The button shou ...

Incorporating the JqueryUI menu into an AngularJS project

We are facing an issue with integrating JqueryUI menus into our AngularJS application. In our Layout.js file, we are attempting the following: OURApp.controller('leftBarCtrl', ['$scope', function ($scope) { $scope.init = function ( ...

When configuring a domain for Express sessions, it prevents the cookie from being stored

I have encountered an issue with my node.js service application and react frontend. I am utilizing Discord OAuth and express sessions for authentication on my application frontend. Everything functions perfectly when running locally, but upon deploying to ...

Is it possible to nest ng-repeat and access $first and $last properties simultaneously

Below is the form that I am currently working with, <tbody ng-repeat="attGroup in attributesGroups"> <tr> <td class="vcenter text-right"> &nbsp;&nbsp;<a href="javascript:" ng-click="!$last && up ...

Is it possible to reload the webpage just one time after the form is submitted?

Can anyone suggest how I can refresh the webpage using PHP after submitting a form? I've been searching for a solution but haven't found one yet. Your assistance would be greatly appreciated. ...

Error message: "Unable to POST image with Node/Express (React frontend) while attempting to upload

I am a beginner in Node.JS and currently working on developing a MERN movie ticket booking system. The front-end code snippet provided below showcases the function responsible for uploading an image for a specific movie: export const uploadMovieImage = ( ...

Implement a feature in JavaScript that highlights the current menu item

I'm currently developing a website at and have implemented a JavaScript feature to highlight the current menu item with an arrow. The issue I'm facing is that when users scroll through the page using the scrollbar instead of clicking on the men ...

Unforeseen outcomes when setting background colors with Anime.js

I've recently started experimenting with Anime.js. I have a piece of code that I'm using to animate a div element with an id of a. anime({ targets: "#a", translateX: 250, color: "#fff", backgroundColor: "hsl(200, 50%, 50%)", ...

Tips for preserving @typedef during the TypeScript to JavaScript transpilation process

I have a block of TypeScript code as shown below: /** * @typedef Foo * @type {Object} * @property {string} id */ type Foo = { id: string } /** * bar * @returns {Foo} */ function bar(): Foo { const foo:Foo = {id: 'foo'} return f ...

Using JavaScript regex to match repeating subgroups

Can a regular expression capture all repeating and matching subgroups in one call? Consider a string like this: {{token id=foo1 class=foo2 attr1=foo3}} Where the number of attributes (e.g. id, class, attr1) are variable and can be any key=value pair. C ...