bbeardall
bbeardall

Reputation: 121

Grunt Concat many files in many folders while maintaining folder structure

I am using Grunt concat in my project. I want to combine files on a folder level. E.G.

js >
  parent >
     child1 >
        a.js
        b.js
        c.js
     child2 >
        a.js
        b.js

into:

js >
  parent >
     child1 >
       child1combined.js
     child2 >
        child2combined.js

is there a way of doing this without specifically adding each "child" in its own concat line?

Upvotes: 1

Views: 329

Answers (3)

Adrian Cerbaro
Adrian Cerbaro

Reputation: 1

I know this topic is old, but I want to share my solution because I couldn't find a simple solution working as expected on the web.

concat: {
        files: [
            {
                expand: true,
                src: ["**/*.js"],
                dest: "dest/js",
                cwd: "src/js",
                rename: function(dst, src) {
                    const srcParts = String(src).split("/");
                    let dstPath = "";
                    let dstName = srcParts[0].split(".")[0];
                    if (srcParts.length > 1) {
                        dstName = srcParts[srcParts.length - 2];
                        dstPath =
                            srcParts
                                .slice(0, srcParts.length - 1)
                                .join("/") + "/";
                    }
                    return `${dst}/${dstPath + dstName}.js`;
                }
            }
        ]
    }

I hope this helps someone :)

Upvotes: 0

bbeardall
bbeardall

Reputation: 121

I ended up doing the following I found in this post.

grunt.registerTask("taskName", "Task Description", function() {

            // get all module directories
            grunt.file.expand("src/js/parent/*").forEach(function (dir) {

                // get the module name from the directory name
                var dirName = dir.substr(dir.lastIndexOf('/')+1);

                // get the current concat object from initConfig
                var concat = grunt.config.get('concat') || {};

                // create a subtask for each module, find all src files
                // and combine into a single js file per module
                concat[dirName] = {
                    src: [dir + '/**/*.js'],
                    dest: 'build/js/parent/' + dirName + '/combined.js'
                };

                // add module subtasks to the concat task in initConfig
                grunt.config.set('concat', concat);
            });
        });

Then just call taskName from your registerTask.

Upvotes: 1

myconode
myconode

Reputation: 2617

Use globbing patterns in your concat task. To quote the linked documentation:

It is often impractical to specify all source filepaths individually, so Grunt supports filename expansion (also know as globbing).

Upvotes: 0

Related Questions