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?
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.
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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With