I am running grunt uglify task to minify my js files but it is giving me error when string started with ` character.
My string look like this
var html = `<div class='list-item'>
<span>ABC</span>
</div>`;
My Gruntfile.js uglifyjs block is like this
uglify: {
'dev': {
options: {
mangle: false
},
files: {
'common/utility_functions.js': ['common/utility_functions.js']
}
}
}
It is giving me following error when i run grunt uglify
>> Uglifying source common/utility_functions.js failed.
Warning: Uglification failed.
SyntaxError: Unexpected character '`'.
Line 162 in common/utility_functions.js
Use --force to continue.
Can anyone help to fix this issue? I think using ` character is valid. It has not given me error during jshint process, because i added enext: true in jshint options.
The grunt-contrib-uglify-es version has now been published to npm. It’s the same harmony branch on GitHub that I mentioned in my previous updated answer below. However, it can be installed directly via npm running the following command:
npm i -D grunt-contrib-uglify-es
Since answering this question a harmony branch of grunt-contrib-uglify
has been made available. This version handles the ES6 Template Literals and other ES6 syntax features.
Installing the harmony branch of grunt-contrib-uglify
:
Firstly uninstall the current version of grunt-contrib-uglify
by running the following command via your CLI:
npm un -D grunt-contrib-uglify
Next install the harmony branch by running:
npm i -D https://github.com/gruntjs/grunt-contrib-uglify.git#harmony
(Note the harmony
branch in not available via the npm registry so we install it directly via GitHub)
Your package.json
will now include the following snippet:
...
"devDependencies": {
...
"grunt-contrib-uglify-es": "git+https://github.com/gruntjs/grunt-contrib-uglify.git#harmony"
...
}
...
Run your uglify
Task as per normal, and you will not encounter the error message.
Your string utilizes the ES6 Template Literal syntax and this feature is not supported by uglify-js (the JavaScript parser/mangler/compressor used by grunt-contrib-uglify
).
See the answer to this post for further info.
If your project requires the use of ES6 features, then consider transpiling your code, using a JavaScript transpiler such as Babel, then uglifying the resultant ES5 code using grunt-contrib-uglify
.
Alternatively, if ES6 Template Literals are the only part of the ES6 syntax that your project uses, there's always the option of reverting to the older syntax instead for your strings. E.g.
var html = '<div class=\'list-item\'' +
'<span>ABC</span>' +
'</div>';
The example code shown above will be handled successfully by grunt-contrib-uglify
.
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