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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With