Search code examples
jsongruntjsgrunt-contrib-concat

Create a dynamic array for use in grunt concat


I need to concatenate a set files based on variables I have defined my package.json.

// package.json
...

"layouts": [
    { 
      "page": "home",
      "version": "a"
    },
    { 
      "page": "about",
      "version": "a" 
    },
    { 
      "page": "contact",
      "version": "b" 
    }
  ]

...

In grunt I am then building these into a JSON array and pumping it into the src parameter in my grunt-concat-contrib task.

// gruntfile.js
...

var package = grunt.file.readJSON('package.json'),
    targets = package.layouts,
    paths = [];

    for (var target = 0; target < targets.length; target++) {
        paths.push("layouts/" + targets[target]['page'] + "/" + targets[target]['version'] + "/*.php");
    };

    var paths = JSON.stringify(paths);

    grunt.log.write(paths); // Writing this to console for debugging

    grunt.initConfig({
        concat: {
            build: {
                src: paths,
                dest: 'mysite/Code.php',
                options: {
                    separator: '?>\n\n'
                }
            }
        }
    });

...

My issue is that the paths variable is not working inside of the initConfig when it is assigned to JSON.stringify(paths).

If I manually input the array like the following that I copied from where I logged the paths variable to the console, it works!

var paths = ["layouts/home/a/*.php","layouts/about/a/*.php","layouts/contact/b/*.php"];

What am I missing?


Solution

  • Derp. I fixed it, I didn't need to JSON.stringify() the array.

    Final working gruntfile is below:

    // gruntfile.js
    ...
    
    var package = grunt.file.readJSON('package.json'),
        targets = package.layouts,
        paths = [];
    
    for (var target = 0; target < targets.length; target++) {
        paths.push("layouts/" + targets[target]['page'] + "/" + targets[target]['version'] + "/*.php");
    };
    
    grunt.initConfig({
        concat: {
            build: {
                src: paths,
                dest: 'mysite/Code.php',
                options: {
                    separator: '?>\n\n'
                }
            }
        }
    });
    
    ...