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

Enhancing w3-import-html with JavaScript

<div id="import" includeHTML="page.html"></div> function getInclude() { var x = document.getElementById("import").includeHTML; //returns 'undefined' alert(x); } function modInclude() { document.getElementById("import") ...

Troubleshooting a Node.js problem with variable scope

I'm working on a nodejs route that downloads a URL as an mp3 using npm-youtube-dl. I have a download directory being monitored with chokidar for new files, and once a file is added, I save the file link. After the download completes, a function is cal ...

Angular.js enables seamless synchronization between contenteditable elements and the $scope object by automatically updating the

I'm completely new to Angular.js and have been exploring various tutorials to grasp the concept of two-way binding with contenteditable elements within an ng-repeat. Currently, I am utilizing a shared 'store' between controllers like this: ...

using ng-show to display array elements

There is a syntax error showing up on the console for the code below, but it still functions as intended. Can someone help identify what I might be missing? <p class="light" data-ng-show="selectedAppType in ['A1','A2','A3' ...

What is the best way to initialize a value asynchronously for React context API in the latest version of NextJS, version

Currently, I'm working on implementing the React context API in my NextJS e-commerce application to manage a user's shopping cart. The challenge I'm facing is how to retrieve the cart contents from MongoDB to initiate the cart context. This ...

Is there a way to override the JSON.stringify method within the JSON class of a TypeScript project without using a custom call?

Dealing with a React Native and TypeScript app here. I keep encountering an error from Fabric every week: "JSON.stringify cannot serialize cyclic structures." The frustrating part is that the error seems to pop up randomly, without any specific scenario tr ...

Prevent clicks from passing through the transparent header-div onto bootstrap buttons

I have a webpage built with AngularJS and Bootstrap. It's currently in beta and available online in (German and): teacher.scool.cool simply click on "test anmelden" navigate to the next page using the menu This webpage features a fixed transparent ...

I'm having trouble getting the JADE tag to render in Express script. Can anyone help me

I am trying to include client-side script in my JADE template and so far I have: extends layout script. function collect_data() { var transitions = {}; $( ":checkbox:checked" ).each(function (index, element) { //// some code ...

Leveraging React Native to position a view absolutely in the center of the screen without obstructing any other components

How can I center an image inside a view in the middle of the screen using position: "absolute"? The issue is that the view takes up 100% of the width and height of the screen, causing all components underneath it (such as input fields and buttons ...

What is the best method to center a div on the screen?

Is there a way to have a div open in the center of the screen? ...

The Markdown-to-jsx tool is having trouble processing the provided source code

Utilizing a Material UI blog post template found at https://github.com/mui-org/material-ui/tree/master/docs/src/pages/getting-started/templates/blog, I have created my React app using npx create-react-app. Upon console logging the source, it displays as a ...

Is it possible to assign multiple ID's to a variable in jQuery?

I am currently using a script for a slider known as Slicebox, and in order to have different image sizes for mobile and desktop views, I need to duplicate the feature on my website. Although it's not ideal, I really like this slider and want to explo ...

Updating a div using PHP elements

Currently, I'm using a webcam to capture images for a project related to learning. My goal is to showcase the recently taken photos. After taking a photo, it gets stored in a folder. To display all the collected photos within a <div>, I need to ...

Struggling with obtaining react-modal in my React Component

Greetings to all React developers out there, especially the newbies like me. I am currently facing an issue with implementing react-modal in my React Component based on this example here. Unfortunately, I have encountered several errors that are proving di ...

Creating stylish error labels using Materialize CSS

While Materialize has built-in support for validating input fields like email, I am looking to implement real-time validation for password inputs as well. This would involve dynamically adding error or success labels using JavaScript. Unfortunately, my at ...

Steps for including a path to a base64 encoded image

I am currently facing a challenge in embedding images into my emails where I need to encode them using an online tool. The issue I am encountering is that the email template I am using has a dynamic URL, with ${loginurl}/images as the path to my image. H ...

A guide on how to assign a placeholder as the default value for a date picker

Currently using Vue3 with options API, and this question does not pertain to date formatting. Looking at the code provided on StackBlitz here, the default format for the date being initially set is dd.mm.yyyy. I am interested in knowing how to set the date ...

Oops! SAPUI5 is encountering an issue with reading property '0' of undefined

Is there a possibility of encountering multiple errors leading to this specific error message? https://i.stack.imgur.com/RpWhw.png Despite searching online, it appears that the error occurs in the JavaScript file when getelementbyid returns null. However ...

Protecting String in PHP to Utilize in JavaScript

When I receive code through AJAX, I handle it as shown below: $verifiedSubject = addslashes(htmlentities($_REQUEST['subject'])); $verifiedBody = addslashes(htmlentities($_REQUEST['body'])); $verifiedAttachment1 = addslashes(htmlentitie ...

Is it possible to generate a triangular attachment below a div element?

My designer sent me a unique design and I'm wondering if it's possible to replicate using HTML, CSS, or JavaScript? https://i.stack.imgur.com/spB71.png I believe it can be done with CSS by creating a separate div positioned absolutely under the ...