Search code examples
javascriptjqueryecmascript-6ecmascript-5uglifyjs

Unexpected character ( ` ) error when using UglifyJS?


While running uglifyjs, I get the above error. The code looks like this:

$('.lazyload').each(function(i,j){
    var h = $(j).attr( 'height' );
    var w = $(j).attr( 'width' );
    var at = `data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${w} ${h}"%3E%3C/svg%3E`;
    $(j).attr('src', at);
});

I read that I would need to transpile it down to ES5, but I'm new to this and I'm not sure how to to that.


Solution

  • uglify-js only supports ECMAScript 5. This explains why you get an error on the line that has the template literal, which is a syntax introduced with ECMAScript 2015:

     var at = `data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${w} ${h}"%3E%3C/svg%3E`;
     //       ^ error
    

    You can do the same assignment without template literal, using single quoted literals and concatenation:

    var at = 'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ' 
           + w + ' ' + h + '"%3E%3C/svg%3E';
    

    Alternatively you could follow the advice on uglify-js home page (github)

    To minify ECMAScript 2015 or above, transpile using tools like Babel.