Search code examples
javascriptgruntjsuglifyjs

Uglify won't let me use variables as keys


I'm using uglify to minify my javascript files, but I ran into an error: When I try to uglify a file that has a variable as key, it throws the following error: Unexpected token: name . line 9.

The line where the error is being thrown is as follows:

var newObject = {[testVariable]: foo[i].bar.$t};

testVariable is an integer, but I cant put the integer as is because it is dynamically generated based on an outside file every reload.

Thanks a lot for the help.


Solution

  • It looks like Uglify does not support ES6 syntax, which the syntax you're using is. You could either use something like Babel to transpile first, or try to find another minifier that does support ES6.

    You could also write your code in ES5 syntax, which is like this:

    var newObject = {};
    newObject[testVariable] = foo[i].bar.$t;