17

I have a project with several sub folders that contain JavaScript files I want to concatenate. what would be the right way to configure them?

eg.

source: /modules/$modulename/js/*.js (several files) dest: /modules/$modulename/js/compiled.js

So what I want to do is to compile js-files of an unknown/unconfigured count of subfolders ($modulename) into one file per subfolder.

Is this possible?


The following function (built after hereandnow78's instructions) does the job:

grunt.registerTask('preparemodulejs', 'iterates over all module directories and compiles modules js files', function() {

    // read all subdirectories from your modules folder
    grunt.file.expand('./modules/*').forEach(function(dir){

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

        // set the config for this modulename-directory
        concat[dir] = {
            src: [dir + '/js/*.js', '!' + dir + '/js/compiled.js'],
            dest: dir + '/js/compiled.js'
        };

        // save the new concat config
        grunt.config.set('concat', concat);

    });

});

after that i put preparemodulejs before the concat job in my default configuration.

Patrick
  • 691
  • 8
  • 30

1 Answers1

32

you will probably need to code your own task, where you iterate over your subfolders, and dynamically append to your concat configuration.

grunt.registerTask("your-task-name", "your description", function() {

  // read all subdirectories from your modules folder
  grunt.file.expand("./modules/*").forEach(function (dir) {

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

    // set the config for this modulename-directory
    concat[dir] = {
     src: ['/modules/' + dir + '/js/*.js', '!/modules/' + dir + '/js/compiled.js'],
     dest: '/modules/' + dir + '/js/compiled.js'
    };

    // save the new concat configuration
    grunt.config.set('concat', concat);
  });
  // when finished run the concatinations
  grunt.task.run('concat');
});

run this with:

$ grunt your-task-name

this code is untested, but i think it should do your job.

HINT: you can put this code into an external file and include in your gruntfile if you want to keep your gruntfile small, e.g. put this into a file inside a tasks-directory:

module.exports = function(grunt) {
  grunt.registerTask("your-task-name", "your description", function() {
    ...
  });
};

and load in in your gruntfile:

grunt.loadTasks("./tasks");
Community
  • 1
  • 1
hereandnow78
  • 14,094
  • 8
  • 42
  • 48
  • @hereannow78 this approach is great, i totally forgot that i can read in the file structure. i'll put an update into the question which function works. – Patrick Jun 12 '13 at 09:07
  • +1 for suggesting `tasks` directory. Too many bloated Gruntfiles out there. – ZenMaster Nov 24 '13 at 08:13
  • This is fairly old, is there any way to exclude folders from the parent directory? – pcnate Feb 21 '17 at 22:22