Search code examples
javascriptnode.jsgrunt-contrib-concat

Grunt Task Runner to concatenate files


I am writing grunt to concatenate files dynamically, for that I have array of files in my grunt.config variable. How to use that in grunt concat.

I am writing grunt.config('jsResources', targetConfig); from dynamically text-replace function. Its returning as array. How to utilize it in grunt concat. I tried this way but thats not worth.

My jsResources is array. My grunt is like

concat: {
    js: {
        //Concatenate all of the files in the jsResources configuration property
        src: ['app/<%= jsResources %>'],
        dest: 'build/views/js/combined.js',
        options: {
            separator: ';\n'
        }
    }            
}

Its repalcing content but can't read content, and concatenate in my combine.js My 'jsResources' is like ['scripts/modules/allModules.js','scripts/config/constants.js','...'] Its creating empty file combine.js.


Solution

  • So I gave it one more try and this is result:

    You need to generate paths before you put them in templated variable. Templated variable here is an object but can be any valid js more info. And inside it you can set properties that have array as values.

    module.exports = function(grunt) {
    
      var myFiles = {
        jsResources: ['file1.js', 'file2.js']
      };
    
      myFiles.jsResources = myFiles.jsResources.map(function(item) { return 'app/' + item; });
    
      // var jsres = myFiles.jsResources; // another way
    
      grunt.initConfig({
        // myFiles: myFiles, // this is also possible instead of grunt.config() below
        concat: {
          dist: {
            src: ['<%= myFiles.jsResources %>'], // src: ['<%= jsres %>'],
            dest: 'dest.js',
          },
          options: {
            separator: '\n'
          }
        }
      });
    
      grunt.config('myFiles', myFiles);
      // grunt.config('jsres', jsres); // another way
    
      grunt.loadNpmTasks('grunt-contrib-concat');
      grunt.registerTask('default', ['concat:dist']);
    
    };
    

    This generates dest.js with content.