Having difficulty in compressing Vue.js application

My Vue.js Application contains the following code snippet:

(function() {
    initApp();
})();

function initApp() {
    window.myApp = new Vue({
        el: '#wrapper',
        data() {
return {
somedata: []
            }
        }
    });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>

Despite successfully running the application, when I attempt to minify the code, it fails with the error

Error : Unexpected token: punc (()
. This leaves me perplexed as to the reason behind it.

Answer №1

These compressors are limited to supporting older versions of JavaScript, specifically up to ES5. To get your code to work properly, you'll need to convert it:

(function() {
    initApp();
})();

function initApp() {
    window.myApp = new Vue({
        el: '#wrapper',
        data: function() { // Updated this line
            return {
                somedata: []
            }
        }
    });
}

By doing this, it should compress as expected.


Details:

They are using uglify-js: "^3.3.10", which is known for not supporting ES6 (use uglify-es for that).

According to their repository (emphasis added):

UglifyJS 3

UglifyJS is a JavaScript parser, minifier, compressor, and beautifier toolkit.

Note:
  • (...)
  • uglify-js only supports JavaScript (ECMAScript 5).
  • To minify ECMAScript 2015 or above, transpile using tools like Babel.

Answer №2

Your compressor is not compatible with ES6

The reason you are encountering this error is because, as mentioned by pacdcjunior, your compressor does not support ES6. (I faced the same issue when transitioning from jQuery to Vue.js, which uses ES6 syntax.)

Resolution: Switch to Terser instead.

Terser is ES6 compliant, actively developed (at the time of writing), and serves as a direct alternative to Uglifyjs.

Extra: Minifying Multiple Files at Once with Terser

To minify a single file using Terser from the command line, use this command:

$ terser file.js -m -o file.min.js

However, if you have numerous files to minify collectively, the process can be cumbersome. I came across this helpful answer and made a slight adjustment. Add the following to your .bash_profile:

alias renderjs='rm *.min.js; for f in *.js; do short=${f%.js}; terser $f -m -o $short.min.js; done'

Access your js directory and execute renderjs. Now, every *.js file will have a minified version. Convenient!

Answer №3

Are you referring to the compiled JavaScript file (app.js)? If so, you can simply compile it for production by running "npm run production".

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

Encountering 'Element not found' error when automating Flight Booking on MakeMyTrip.com using Selenium WebDriver, specifically while trying to select a flight after conducting a search

Currently in the process of automating the flight booking feature on MakeMyTrip.com using Selenium WebDriver. I have implemented separate classes for Page Object Model (POM) and TestNG. The code successfully automates the process up to the point of clicki ...

A technique in JavaScript that allows for assigning object property values using an external variable

I need to clarify my situation with a code example const faultLine = new google.maps.Polyline({ paths: [ new google.maps.LatLng(49.95, -128.1), new google.maps.LatLng(46.26, -126.3), new google.maps.LatLng(40.3, -125.4) ] }); ...

The navigation menu dissolves into hiding at the uppermost part of the page upon scrolling upwards on iOS devices

I am currently working on creating a navigation menu that will automatically hide when scrolling down and reappear when scrolling up. This functionality works perfectly fine on desktop and Android browsers, but I have encountered an issue specifically with ...

What differences occur in JavaScript when the IE Developers Tools are accessed?

When the IE Developers Tools are opened, what changes in terms of running an AJAX application? I am currently investigating a mysterious bug related to PrimeFaces dropdown lists in Internet Explorer. Sometimes these dropdowns do not open when clicked, but ...

Module not found in Node.js Express JS

I've read several topics on this issue here at stackoverflow, but I am still unable to get my node application running. When I try to run the command: node app.js local I receive the following error: Error: Cannot find module './config' ...

Middleware that handles form post requests quickly became overwhelmed and resulted in a RangeError

Currently, I am working with a form using ejs templates to collect data. When accessing the "/" route, my application renders the "main" view and utilizes a middleware to handle the form data. However, I encountered an error stating "RangeError: Maximum ca ...

Updating route in AngularJS does not populate data (ngRepeat)

Just starting out and trying to figure things out, so bear with me if this is a basic issue. I have two routes set up. localhost:3000 displays a list of objects, while localhost:3000/:slug shows detailed information about a specific product. The initial ...

Getting the result from a JavaScript request, whether it's synchronous or asynchronous

This code snippet involves a function that starts with a synchronous comparison test == 0. If the comparison is true, it returns one piece of content; however, if it's not, an asynchronous request is made. The goal here is for the latter part to retur ...

Dynamic CSS class alteration on scrolling using Vue.js

I am currently in the process of developing a web application using vueJs and bootstrap. I am interested in figuring out how to dynamically change the CSS class of an element based on scrolling behavior. Is there a vue-specific method that can achieve this ...

Creating a Utils class in Vue.js with seamless access to Vuex through this.$store

I have a situation where I need to retrieve state from the Vuex store using this.$store. After some research, I discovered that creating a custom plugin with an installed instance method might be the solution. Here is my plugin implementation: index.ts i ...

Encountering the "Cannot set headers after they are sent to the client" error within an Express.js application

In my recent project, I created a middleware to authenticate users and verify if they are verified or not. Initially, when I access protected routes for the first time, everything works fine and I receive success messages along with verification of the JWT ...

Transforming a flat TypeScript array into a nested object structure

I'm working on implementing a user interface to offer a comprehensive overview of our LDAP branches. To achieve this, I plan to utilize Angular Materials Tree as it provides a smooth and intuitive browsing experience through all the branches (https:// ...

What is the best way to display a number or integer using axios?

Need help retrieving the integer from the response obtained through an axios get request Here is what I see in the console log: https://i.stack.imgur.com/ztmf0.png setDappList([response.data.stats]); <div>{setDappList.total}</div> Unfortuna ...

I am looking for a way to write a function that will emit an event to the parent component when an icon is

I am creating an input element with an icon to show/hide the password. How can I emit an event in the v-icon to notify the parent component when the icon is clicked? Here is my child component BaseInputPassword: <div class="label"> ...

Error encountered while using Chart.js with JSON dataset

Struggling to make this work... Here are the necessary scripts: <script src="Chart.js"></script> <script src="jquery-1.11.3.min.js"></script> This is the full code I am working with: <body> <div id="chartCanvas"> &l ...

To ascertain whether the mouse is still lingering over the menu

I have a condensed menu construction that unfortunately cannot be changed in HTML, only CSS and JS modifications are possible! $('span').on("hover", handleHover('span')); function handleHover(e) { $(e).on({ mouse ...

In JavaScript, when a div element contains an iframe, the click event will not trigger on the div

Check out this sample HTML markup: <div> <iframe></iframe> </div> The iframe is set to fill the outer div. I've added an event handler to the div click event: div.addEventListener("click", function () { console.log( ...

What could be the reason my CSS and Javascript animation is not functioning properly?

Currently working on creating a dynamic animation menu using CSS and Javascript, but encountering some issues. The concept involves having a menu with initially hidden opacity (using CSS), which becomes visible when the hamburger menu is clicked, sliding i ...

Comparing two tables in jQuery/Javascript for matching data

I want to check for matches between the rows of two HTML tables, where the data in the first cell can be duplicated but the data in the second cell is always unique. The goal is to determine if the combination of values in the first and second cells of tab ...

Discovering common elements in various arrays of objects

Details: record1 = [{"site": "The Blue Tiger", "zipcode": "E1 6QE"}, {"site": "Cafe Deluxe", "zipcode": "E6 5FD"}] record2 = [{"site": "Blue Tiger", "zi ...