Is there a way to convert arrow functions in vue files through transpilation?

I have developed a Vue application that needs to function properly in an ES5 browser (specifically iOS 9).

One issue I've encountered is that some of the functions within the Vue components are being transformed into Arrow functions: ()=>, which is causing compatibility problems with iOS 9 Safari. What's puzzling is why some functions are transpiled correctly while others are not.

For example, consider this snippet from a Vue component:


data() {
    return {
        birthday: '',
        accepted: false,
        acceptedForSelectedKids: false
    };
},
computed: {
    dataPrivacyLink() {
        return settings.data_privacy_link;
    },
    isOverFifTeen() {
        if (this.privacyToEdit && this.privacyToEdit.owner.age) {
            return this.privacyToEdit.owner.age > 15;
        }
        if (this.birthday) {
            return differenceInCalendarYears(new Date(), new Date(this.birthday)) > 15;
        }
        return false;
    }
}

The data and dataPrivacyLink functions are transpiled into arrow functions, but for some reason the isOverFifTeen function is not.

Here is how it appears after being transpiled:


data:()=>({birthday:"",accepted:!1,acceptedForSelectedKids:!1}),computed:{dataPrivacyLink:()=>settings.data_privacy_link,isOverFifTeen(){return this.privacyToEdit&&this.privacyToEdit.owner.age?this.privacyToEdit.owner.age>15:!!this.birthday&&function(e,t){Object(c.a)(2,arguments);var o=Object(a.a)(e),n=Object(a.a)(t);return o.getFullYear()-n.getFullYear()}(new Date,new Date(this.birthday))>15}

This behavior may be attributed to how webpack is configured:


                {
                    test: /\.vue$/i,
                    loader: 'vue-loader'
                },
                {
                    test: /\.js$/,
                    loaders: ['babel-loader'],
                    exclude: [/node_modules/]
                },

Additionally, this is the babel.config.js file:


module.exports = {
    presets: [['@babel/preset-env', { modules: false }]],
    plugins: ['@babel/plugin-syntax-dynamic-import'],
    env: {
        test: {
            presets: [['@babel/preset-env']]
        }
    }
};
    

In the package.json file, I specified the targeted browsers in the browserslist:


"browserslist": [
    "> 0.5%",
    "last 2 versions",
    "not ie <= 11",
    "ios_saf >= 9",
    "not dead"
]
    

How can I prevent these arrow functions from being used?

Answer №1

For those utilizing Webpack 5, it is essential to explicitly define the functionalities that need to be transpiled within the ouput.environment setup as provided in this documentation: https://webpack.js.org/configuration/output/#outputenvironment.

output: {
  // ... other configurations
  environment: {
    arrowFunction: false,
    bigIntLiteral: false,
    const: false,
    destructuring: false,
    dynamicImport: false,
    forOf: false,
    module: false,
  },
}

Answer №2

Make sure to include the plugin in your babel.config.js file

module.exports = {
    presets: [['@babel/preset-env', { modules: false }]],
    plugins: [
      '@babel/plugin-syntax-dynamic-import',
      '@babel/plugin-transform-arrow-functions' // remember to add this
    ],
    env: {
        test: {
            presets: [['@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

Scrolling back to the top of the page using Jquery instead of a specific div

Check out the code for my project here. The isotope feature is functioning correctly, however, when clicking on the image, instead of scrolling to the navigation under the red box as intended, the page scrolls all the way to the top. If I modify the follo ...

Nuxt - Issue persisting logged in state on refresh despite information being stored in local storage and cookies

I am facing an issue where the state gets cleared on refresh, even though the token, userid, user email, and expiration date are stored in local storage and cookies. I suspect there might be a problem with the store or something else needs to be done to re ...

Navigating the NextJS App Directory: Tips for Sending Middleware Data to a page.tsx File

These are the repositories linked to this question. Client - https://github.com/Phillip-England/plank-steady Server - https://github.com/Phillip-England/squid-tank Firstly, thank you for taking the time. Your help is much appreciated. Here's what I ...

Attempting to replace the checkbox image resulted in no changes

<?php require 'includes/configs.inc.php'; ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title><?php $site_name ?></titl ...

Having trouble selecting a default option in a dynamically populated select dropdown using ng-model in the dropdown

For my Angularjs application, I needed to dynamically return a select drop down with its selected option. To accomplish this, I implemented the following function: function getCellRendererMapping(data) { if (data.order == 6) { return funct ...

Utilizing Next.js routing to accommodate two distinct subdomains on a single website

I am looking to develop a new platform using Next.js (React.js and React-router). The platform will have two distinct spaces - one for users and another for the owner to manage all users. To achieve this, I plan on splitting both areas into two subdomains: ...

Adjust background image size to fit the screen, not just the content

Whenever I set the background image for each page using the following JavaScript code, var imageUrl = 'url(' + imageUrl + ') top left no-repeat fixed'; $('body').css({ 'background': imageUrl }); I also add ...

Detecting collisions between two squares in an HTML5 canvas

class Snake { constructor() { this.x = 400; this.y = 400; this.width = 25; this.height = 25; } draw() { ctx.fillRect(this.x, this.y, this.width, this.height); } } let snake = new Snake(); class ...

Is it possible to switch from kilometers to miles on the distance matrix service in Google Maps?

let distanceService = new google.maps.DistanceMatrixService(); distanceService.getDistanceMatrix({ origins: [sourceLocation], destinations: [destinationLocation], travelMode: google.maps.TravelMode.DRIVING, unitSystem: google.maps.UnitSystem.IMPERI ...

Unable to capture DOM events on the component within the hosting component

I have a Vue component with several objects called lines. I am creating a table from these lines using different components based on the type of line. Everything is working perfectly fine. Below is a simplified version of the component: <template> ...

The value of msg.member is empty following the messageReactionAdd event

Whenever someone reacts on my server, it triggers the messageReactionAdd event. However, I am encountering difficulty in retrieving the member object of the author of a message that someone reacted to: module.exports = async (client, messageReaction, user) ...

The first item in Swiper is incorrectly displayed after the initial cycle, even though the data is accurate

Currently, I am incorporating the slider functionality in Vue using the Swiper framework. Although everything seems to be functioning properly, there is a minor issue that arises when filtering the data and completing the first cycle after scrolling. The f ...

Learn how to show image information in a separate div by clicking on the image using jQuery

Is there a way to show or hide information of an image in a separate div by clicking on the image itself? $(document).ready(function () { $(".cell").click(function () { $(this).find("span").toggle("slow"); }) }); <div class="cell"> ...

Verifying if form submission was done through AJAX using PHP

Hey there, I need some help with checking whether or not this ajax method has been submitted. I want to display the result based on a certain condition. Below is the code for the Ajax POST request: $.ajax({ url: "addorderInfo.php", // This ...

Encountering an issue with React and Vercel: Why is the command "npm run build" exiting with code 1?

I've been encountering an issue while trying to deploy a simple create-react-app on Vercel. The build log keeps showing the error mentioned in the title. Does anyone have a solution for this? I recently forked and cloned two repositories - one contain ...

What is the best way to deactivate the first two columns of the header in Vue?

I am attempting to deactivate the draggable function for the first 2 columns. I have tried using options in the draggable plugin. :options="{disabled : 'Subject'}" However, this disables the draggable functionality for all headers. < ...

Relocate the preview division below the button in the Kartik File Input Widget

There are two input file buttons that allow users to upload an image on each button. Upon selecting an image, a preview of the image will be displayed above the button. The current layout is shown here: When images of different sizes are uploaded, the but ...

I am experiencing difficulties with the state updates, as they are not displaying my products correctly when I select them from

When updating the states setProductsShow and setSelectedCategories, it is important to note that setSelectedCategories is updated before setProductsShow. This sequence is crucial for rendering products correctly. I have come across numerous solutions rega ...

Finding the current index or count of an array based on the parent V-for array in VueJs

I am facing an issue with my nested v-for loop setup. Here is how it currently looks: <div class="category" v-for="(category, categoryIndex) in categories"> <div class="product" v-for"(product, productIndex) in cateogry)"> {{produc ...

Retrieving information from a JSON source to populate a data table

Hello fellow developers... I'm currently facing an issue while trying to dynamically populate a data table with information fetched through a fetch request and stored in a Vuex instance variable. Here is the relevant code snippet: <script> impo ...