Search code examples
javascriptgulpuglifyjs

Why pushing object to array causes Gulp Uglify to crash


I have gulpfile which is supposed to minify my js files normally. I have one function, which runs each loop having following line:

newArr.push({[keyName]:val});

This one particular line causes the uglify to fail.

The whole function is this:

function convertArrToNestedObjArr(arr, keyName) {

    var newArr = [];
    if(arr) {

        $.each(arr, function(k, val) {

            newArr.push({[keyName]:val});
        })
    }
    return(newArr);
}

Gulp process gives the following error:

stream.js:94 throw er; // Unhandled stream error in pipe. ^ Error at new JS_Parse_Error (eval at ...


Solution

  • You've said this code is in a file destined to send to a browser that's being uglified in a gulp process.

    That line is using ES2015's computed property name notation. I suspect the minifier just doesn't understand that yet. If it does, a fair number of browser JavaScript engines in the wild don't, yet.

    If that's the problem, transpile before uglifying (perhaps with Babel or Traceur), or replace

    newArr.push({[keyName]:val});
    

    with

    var o = {};
    o[keyName] = val;
    newArr.push(o);