Having trouble with @babel/plugin-proposal-optional-chaining in Vue.js <script> tag

While working on my vue/vuetify project and attempting to implement optional chaining, I consistently run into an error:


./src/App.vue?vue&type=script&lang=ts& (./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/App.vue?vue&type=script&lang=ts&) 155:24
Module parse failed: Unexpected token (155:24)
File was processed with these loaders:
 * ./node_modules/cache-loader/dist/cjs.js
 * ./node_modules/vue-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
|         }
| 
>         const baz = obj?.foo?.bar?.baz // 42
| 
|         const safe = obj?.qux?.baz // undefined

I have installed

@babel/plugin-proposal-optional-chaining
by using the command
yarn add @babel/plugin-proposal-optional-chaining --dev

In my App.vue file, within the created() function, I have the following code:

const obj = {
  foo: {
    bar: {
      baz: 42,
    },
  },
}

const baz = obj?.foo?.bar?.baz // 42
const safe = obj?.qux?.baz // undefined

console.log({ baz, safe })

The configuration in my babel.config.js is as follows:

module.exports = {
    presets: [
        [
            "@babel/preset-env",
            {
                targets: {
                    node: "current",
                },
            },
        ],
    ],
    plugins: ["@babel/plugin-proposal-optional-chaining"],
}

I am running vue version 2.6.9.

It seems like everything should be functioning correctly after this setup, but the only similar issue I could find is referenced here: https://github.com/vuejs/vue-loader/issues/1697, even though I am using Babel and not TypeScript.

Answer №1

Perhaps you've already resolved this issue, but I encountered the same problem and found that integrating the babel configuration directly into webpack fixed it for me. The necessary settings are now included in @babel/preset-env, so there's no need to separately install the plugin.

Here is an example of how you can add the babel configuration in your vue.config.js:

module.exports = {
  configureWebpack: {
    module: {
      rules: [
        {
          test: /\.m?js$/,
          exclude: /(node_modules|bower_components)/,
          use: {
            loader: 'babel-loader',
            options: {
              presets: ["@vue/app", '@babel/preset-env']
            }
          }
        }
      ]
    }
  },

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

Encapsulating data with JSON.stringify

I'm currently working on creating an object that has the following structure: let outputOut = { "_id": id[i], "regNum": code[i], "sd": sd[i], "pd": ptOut, "p": p[i], ...} //output fs.writeFile('./output/file.json', JSON ...

What is the best way to position an image alongside text using Vue and Buefy?

I'm looking to add an image next to my text in Vue using Buefy. Take a look at the code I have so far, can someone offer some guidance? <template> <section class="hero is-link is-fullheight-with-navbar"> <div cla ...

What could be causing my image not to show up on ReactJS?

I'm new to ReactJS and I am trying to display a simple image on my practice web app, but it's not showing up. I thought my code was correct, but apparently not. Below is the content of my index.html file: <!DOCTYPE html> <html> & ...

What is the process for searching a specific column in a Vuetify v-data-table that is not included in the headers?

Header for Product Data: headers: [ { text: "Product Name", value: "name" }, { text: "Quantity", value: "quantity" }, { text: "Price", value: "price" }, { text: "Orders", value: &quo ...

Is it possible to utilize a JavaScript variable in this particular scenario and if so, what is the

let myVariable = <?php echo json_encode($a[i want to insert the JS variable here]); ?>; Your prompt response would be highly valued. Many thanks in advance. ...

Having trouble with element.scrollTo not functioning properly on mobile devices?

I have been working on creating a vertical scrolling carousel, and so far everything seems to be functioning well. I can scroll horizontally using buttons and swipe gestures successfully on the simulator. However, when I view the website on a real mobile d ...

Is there a way to track when the Angular DTOptionsBuilder ajax call is complete and trigger a callback function?

Working with angular datatables, I have the following code: beforeSend:</p> success callback causes the table on the page not to populate with the data. How can I implement a callback that triggers once the ajax is done without interfering with the ...

Using Redux saga: passing arguments to axios instance

I need to transition my code from thunk to saga to meet the requirements of my company. While it was easy to send api requests with params using thunk, I am struggling to figure out how to pass params to the axios request: redux/sagas/handlers/marketpla ...

How can you switch the display between two different class names using JavaScript?

I currently have a total of four filter buttons on my website, and I only want two of them to be visible at any given time. To achieve this, I labeled the first set of buttons as .switch1 and the second set as .switch2. Now, I've added a 'switch ...

When the `back` button is clicked in a browser from a different domain, does it trigger a page reload?

Imagine a scenario where a user accesses mydomain.com. At this point, the history stack contains only one entry. Then, the user clicks on a link within my website that leads to mydomain.com/cool, causing another state to be pushed onto the stack. Now, with ...

What is the method for retrieving a value from my Node.js module once it has been modified by an asynchronous function?

Apologies, but as a beginner developer, I'm struggling to see how this relates directly to the questions already mentioned. I have no understanding of ajax and I'm unsure how to adapt the solutions provided to my own situation. Currently, I&apos ...

Issue with dynamically filling a form field using ValidityState

I have been utilizing the ValidityState interface for client-side form validation, but I've encountered an issue. Whenever my form is populated programmatically, such as after making a call to a third-party API, the tooLong state always returns false, ...

Tips for bringing a particular tab into focus when a page initially loads

My webpage features custom links (tabs) that display content when clicked. By default, the first tab is selected and its content is shown, while the rest are set to display:none. Clicking on any other link will assign the 'selected' class to it, ...

Using Ajax to poll a Celery task

I am working on a Celery task that updates a PostgreSQL database gradually. In my Django application, I want to fetch the latest data from the database and display it in a template in real-time as the task progresses. I am looking to implement this real-ti ...

Ways to combine duplicate entries within a column using Ruby on Rails?

I need some help with a filtering issue related to sign names. I am trying to merge the content together if there is more than one name of the sign. You can refer to the image attached for better clarity, where I have two server names but I only want to di ...

What is the best way to use jQuery to set the height of one div equal to another div

Edited: I am facing a situation with a 3-column layout - Column A, Column B, Column C. The height of Column A is dynamic and I need to set the same height for both Column B and C. For instance, Column A contains a tabbed panel with varying heights based ...

What is the best way to continuously compare two date variables every minute using Javascript?

In my script, I have two date variables - one representing the current time and the other two minutes later. My goal is to compare both values every minute and trigger a function when the current time is greater than or equal to the latter time. Unfortun ...

How can I dynamically change the className attribute in a Vue v-for loop?

Just starting out with Vue.js and I have a question: I've been attempting this: <li v-for="(msg,index) in system_message" :class="index"> To create different classNames like 0,1,2,3 for each li element. Unfortunately, v-bin ...

The function persists in outputting a true result, despite the fact that it is expected to output

Currently, I am working on a NextJS project where I have a client-side form. I've been attempting to implement validation for the form by creating a separate function called validateForm(). However, no matter what input is provided, the function alway ...

Create a form action dynamically with JavaScript

html code : <section class="main"> <form class="form-4" name="form4" id="form4" method="POST"> <p class="submit"> <button type="submit" name="submit" onclick="show()"><i class="icon-thumbs-up icon-large"></i> ...