0

I need to recursively concat the JavaScript files contained within a directory but ensuring that the files within the current directory be added before digging into the other contained directories, ex:

src/
 - module1/
    - config.js
    - index.js
 - module2/
    - index.js
 - main.js

Using the solution presented in here, I was able to recursively get the files with this:

// get all module directories
    grunt.file.expand("src/*").forEach(function (dir) {
        // get the module name from the directory name
        var dirName = dir.substr(dir.lastIndexOf('/') + 1);

        // create a subtask for each module, find all src files
        // and combine into a single js file per module
        concat.main.src.push(dir + '/**/*.js');
    });

    console.log(concat.main.src);

but when I check into the concat.main.src then the order isn't the way I needed:

//console.log output
['src/module1/**/*.js',
 'src/module2/**/*.js',
 'src/main.js']

The order I need is:

['src/main.js',
 'src/module1/**/*.js',
 'src/module2/**/*.js']

Any ideas on how can I achieve this?

Community
  • 1
  • 1
YadirHB
  • 168
  • 14

2 Answers2

1

The quick fix would be to rename main.js to app.js as it processes alphabetically.

But if u want to keep main.js, try pushing it into the array first. Then if you change the glob for file expand to look only subdirectories of src, then it will skip main.js and continue to add your modules to array

concat.main.src.push('src/main.js');
// get all module directories
grunt.file.expand("src/**").forEach(function (dir) {
    // get the module name from the directory name
    var dirName = dir.substr(dir.lastIndexOf('/') + 1);

    // create a subtask for each module, find all src files
    // and combine into a single js file per module
    concat.main.src.push(dir + '/**/*.js');
});

console.log(concat.main.src);
Dan
  • 774
  • 5
  • 11
  • The main.js is just an example, the truth is in the root directory can exist n files and I want to get a solution which ensures the same behavior by levels which also can be n. The above was just for describe what I need, but I don't think this is the proper solution. Anyways thanks a lot!!! – YadirHB Oct 13 '16 at 00:35
0

thanks a lot!!!

My head went clear after a shower and reviewing deeper in Grunts documentation, I found a solution which let here to other who may be interested. It's using the grunt.file.recurse instead of grunt.file.expand.

var sourceSet = [];
grunt.file.recurse("src/main/", function callback(abspath, rootdir, subdir, filename) {
    sourceSet.push(abspath);
});

concat.main.src = concat.main.src.concat(sourceSet.sort());

Now works perfectly!!!

YadirHB
  • 168
  • 14