Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Grunt to iterate over templates

I'm building a grunt file, and I have 2 folders that need the same grunt tasks applied to them. I would like to be able to use the grunt template property to iterate over each folder so that I don't have to bloat my grunt config object by repeating the configuration objects. Like so:

app1: {
  name: 'app1',
  src: ['src/app/<%= app1.name %>'],
  jsTpl: ['<%= distdir %>/<%= app1.name %>/templates/**/*.js'],
  js: '<%= app1.src %>/**/*.js'
},
app2 {
  name: 'app2',
  src: ['src/app/<%= app2.name %>'],
  jsTpl: ['<%= distdir %>/<%= app2.name %>/templates/**/*.js'],
  js: '<%= app2.src %>/**/*.js'
},
concat: {
  app1: {
    src: ['<%= app1.src %>'],
    dest: ['dist']
  },
  app2: {
    src: ['<%= app2.src %>'],
    dest: ['dist/<%= app2.name %>']
  }
 }

It would be ideal and very DRY to not have to repeat app1 and app2—rather, it would be awesome to have them grouped together through some configuration. But I can't seem to figure out how to do it. Thanks for any help!

Thanks!

like image 353
nikk wong Avatar asked Jul 28 '15 08:07

nikk wong


1 Answers

Grunt is just an ordinary JS, so you can create a function to generate your configuration objects.

function appConfig(appName){
    return {
        name: appName,
        src: ['src/app/' + appName],
        jsTpl: ['<%= distdir %>/' + appName + '/templates/**/*.js'],
        js: 'src/app/**/*.js'
    };
}

Then simply call this function when setting your config

app1: appConfig('app1'),
app2: appConfig('app2'),
concat: {
    app1: {
        src: ['<%= app1.src %>'],
        dest: ['dist']
    },
    app2: {
        src: ['<%= app2.src %>'],
        dest: ['dist/<%= app2.name %>']
    }
}
like image 87
Ulan Murzatayev Avatar answered Sep 28 '22 15:09

Ulan Murzatayev