Search code examples
gruntjsgrunt-contrib-concat

Grunt. Programmatically merge corresponding files in parallel folders with concat


that's my first post on StackOverflow!:D I mean... ever!

Anyway... I couldn't find any clear answer to this, and maybe I'm missing something really obvious. I'm really new to Grunt as well. I'm looking for a way to merge parallel css files in two different folders in few lines of code. So a better solution than doing this for each couple of files:

concat : {
  options : { separator : '\n' },
      css : {
        files:{

          '<%= pkg.dest %>/app/css/main_blue.css' :
            [ 'app/css/base/main_blue.css', 'app/css/extended/main_blue.css' ],

          '<%= pkg.dest %>/app/css/main_red.css' :
            [ 'app/css/base/main_red.css', 'app/css/extended/main_red.css' ],

          '<%= pkg.dest %>/app/css/home.css' :
           [ 'app/css/base/home.css', 'app/css/extended/home.css' ],
          ...
          '<%= pkg.dest %>/app/css/.../foo/bar/xx.css' :
            ['app/css/base/.../foo/bar/xx.css', 'app/css/extended/.../foo/bar/xx.css' ]
          ...
        }
    }
}

Any Grunt guru out there that can help? :)


Solution

  • You could build the config object that you pass to grunt.initConfig dynamically.

    var config = {}; // <- your grunt config
    var files = ['blue', 'red', 'home'];
    for (var i = 0; i < files.length; i++) {
      config['concat']['options']['css']['files']['<%= pkg.dest %>/app/css/'+files[i]+'.css'] = [ 'app/css/base/'+files[i]+'.css', 'app/css/extended/'+files[i]+'.css' ];
    }
    grunt.initConfig(config);