Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to minify Vue.js application

I have a Vue.js Application with the following excerpt of code:

(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>

When I try to minify it, it fails with the error Error : Unexpected token: punc (() but the application runs successfully. I'm not sure why?

like image 654
Asa Carter Avatar asked Apr 08 '18 20:04

Asa Carter


Video Answer


2 Answers

Those compressors simply only support an old version of JavaScript. Their support is restricted to at most ES5. To make your code work, convert it:

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

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

And it should compress.


Details:

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

From their repo (emphasis mine):

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.
like image 84
acdcjunior Avatar answered Oct 21 '22 04:10

acdcjunior


Your compressor isn’t ES6 compliant

You’re getting that error because, like pacdcjunior's said, your compressor isn’t ES6 compliant. (I got your same error when I switched from jQuery to Vue.js—using ES6 syntax.)

Solution: Use Terser instead.

It’s ES6 compliant, in active development (at the time of writing), and is a direct replacement for Uglifyjs.

Bonus: How to minify lots of files in one pass with Terser

You can minify a single file in Terser from the command line like this:

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

But if you have a load of files to minify in one go, that will be tedious. I found this excellent answer and modified it just a little. Add this 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'

Navigate to your js directory and run renderjs. Now all your *.js files have a minified version. Nice!

like image 39
elbowlobstercowstand Avatar answered Oct 21 '22 03:10

elbowlobstercowstand