Search code examples
gruntjsgrunt-contrib-uglify

Grunt uglify : Weird behavior


I cannot figure out why uglify does not want concat string as input or output ...

This works :

uglify: {
    dev_uglify_js: {
        files: {
            'my_file.min.js': ['my_file.js']
        }
    }
}

For example, this does not works :

uglify: {
    dev_uglify_js: {
        files: {
            'my'+'_file.min.js': ['my_file.js']
        }
    }
}

Do you have any idea why ? The output error is "SyntaxError: Unexpected token".

The real insterest here is to concatenate a timestamp to the file name. But just with 2 strings it does not work so ...

Thanks for your help !


Solution

  • In JavaScript, an object key cannot be declared dynamically. This is not a problem with grunt or uglify - it's a language constraint.

    myObject = { 'a' + 'b' : 'b' } // NOPE!
    

    However, any object property can be accessed via square brackets. For example:

    myObject = { 'banana': 'boat' }
    myObject.banana // boat
    myObject['banana'] // boat!
    

    Therefore, you can add properties after the object is already created, using the square brackets syntax.

    myObject = {} 
    myObject[ 'a' + 'b' ] = 'b' // Yes
    myObject.ab // b
    

    The Gruntfile example

    In your Gruntfile, you're bound to, at some point, call something like grunt.config.init or grunt.initConfig. This is usually done inline:

    grunt.initConfig({
      uglify: {} // properties ...
    });
    

    However, initConfig simply receives an object. You can define it and manipulate it as much as you need before calling this function. So, for example:

    var config = { uglify: {} };
    config.uglify['such'+'dynamic'+'very'+'smarts'] = {};
    grunt.initConfig(config);
    

    Similar questions:

    How do I create a dynamic key to be added to a JavaScript object variable

    How do I add a property to a JavaScript object using a variable as the name?