Search code examples
gruntjsgrunt-contrib-concatgrunt-contrib-uglify

Complex gruntjs tasks


I have the following scenario:

  1. concat some files
  2. uglify some files (based on the concatinated ones)
  3. concat a files to another file (that was uglified above)

How would I write gruntfile.js?

I tried something as this but it didn't work.

Thanks

module.exports = function(grunt) {
grunt.initConfig({
    pkg:grunt.file.readJSON('package.json'),
    concat: {
        target: {
            files: [{
    "dest/js/admin.main.js": ["js/spa.js", "js/spa.library.js"],
    "dest/js/jquery-1.min.js": ["js/jquery.min.js", "js/jquery-ui.min.js"]
   }]}
    },
    uglify: {
        target: {
            files: [{
                "dest/js/admin.main.min.js": ["dest/js/admin.main.js"],
                "dest/js/jquery-2.min.js": ["js/jquery.loadingoverlay.js"]
            }]
         }
     },
     concat: {
        target: {
            files: [{
                "dest/js/jq.min.js": ["dest/js/jquery-1.min.js", "dest/js/jquery-2.min.js"]
            }]
        }
    }
});

grunt.loadNpmTasks("grunt-contrib-concat");
grunt.loadNpmTasks("grunt-contrib-uglify");

grunt.registerTask("default", ["concat", "uglify"]); 

};

Solution

  • In grunt you can only define the config for a task once, but you can define multiple targets (with different names). So in your case you need to define two targets under the 'concat' task and then call them in sequence:

    module.exports = function(grunt) {
      grunt.initConfig({
        pkg:grunt.file.readJSON('package.json'),
        concat: {
          step1: {
            files: [{
              "dest/js/admin.main.js": ["js/spa.js", "js/spa.library.js"],
              "dest/js/jquery-1.min.js": ["js/jquery.min.js", "js/jquery-ui.min.js"]
            }]
          },
          step2: {
            files: [{
                "dest/js/jq.min.js": ["dest/js/jquery-1.min.js", "dest/js/jquery-2.min.js"]
            }]
          }
        },
    
        uglify: {
          target: {
            files: [{
                "dest/js/admin.main.min.js": ["dest/js/admin.main.js"],
                "dest/js/jquery-2.min.js": ["js/jquery.loadingoverlay.js"]
            }]
           }
        },
      });
    
      grunt.loadNpmTasks("grunt-contrib-concat");
      grunt.loadNpmTasks("grunt-contrib-uglify");
    
      grunt.registerTask("default", ["concat:step1", "uglify", "concat:step2"]); 
    };