Uglification failed. Unexpected character '`'
Asked Answered
P

3

12

gulp-uglify is unable to uglify this piece of code:

    var alertString = `<?xml version="1.0" encoding="UTF-8" ?>
        <document>
          <alertTemplate>
            <title>${title}</title>
            <description>${description}</description>
          </alertTemplate>
        </document>`

it complains at the character: `. The character is valid for the apple's JS framework. I can't see anything inside the uglify package to ignore those characters and the text string inside it. Am i missing something from the documentation?

Parotitis answered 21/12, 2015 at 14:45 Comment(0)
P
18

Gulp-uglify has yet no official support for ECMAScript 2015 (aka ES6, aka Harmony) but with a little modification the on-development repository can be used.

How-to:

  1. Open Console and enter

cd node_modules/gulp-uglify

  1. Edit package.json

dependencies": { "uglify-js": "git+https://github.com/mishoo/UglifyJS2.git#harmony" },

  1. Console enter:

npm update

And it is ready to run .pipe(uglify()) again


Alternate Solution

  1. Download the following via npm:

npm install --save-dev gulp-uglify gulp-babel babel-preset-es2015

  1. Add the following requires in the gulpfile.js:

var babel = require('gulp-babel'), uglify = require('gulp-uglify');

  1. The gulp task will be as follow:

gulp.task('uglify', function(){ gulp.src('*.js') .pipe(babel({ presets: ['es2015'] })) .pipe(uglify().on('error', function(e){ console.log(e); })) .pipe(gulp.dest('js')); });

What this does is transpile all the EcmaScript 2015 JS code to EcmaScript5 and then uglifies it.

Parotitis answered 22/12, 2015 at 8:38 Comment(2)
this is a gulp solution and your question starts with grunt. Did you switch to gulp?Ory
@JonHarding Oh, yes. I completely overlooked it. Thank you for pointing it out. When I switched to gulp I had the same issue, but it was easier to find a solution. I'll edit the answer since I had the same issue with gulpParotitis
S
2

ES6 is supported in a newer version of gulp-uglify called gulp-uglify-es. If you are using Gulp 4 you can also use .browserlistrc. Below are examples of a project I am using that needs Chrome and Firefox 56 support.

gulpfile.js

    const uglify = require('gulp-uglify-es').default;

    .pipe(babel({
        presets: ['@babel/preset-env'],
        compact:false
     }))
     .pipe(uglify())

.browserlistrc (read more on browserlist)

last 2 chrome versions
firefox 56
Saith answered 14/11, 2019 at 18:3 Comment(0)
M
0

Using Flask + Jinja2 I've solved similar problem as following:

  1. Flask

    render_template('template.html', text='"+`Text\nhere`+"')

  2. Apply uglify ...

  3. JS

    var result = "{{text}}"; // ---> "" + `Text\nhere` + "";

Mast answered 1/12, 2020 at 23:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.