Bruno Monteiro
Bruno Monteiro

Reputation: 712

Grunt: How to run task only for modified file?

I have the following gruntfile.js:

module.exports = function(grunt) {
  require('jit-grunt')(grunt);

  grunt.initConfig({
    uglify: {
      options: {
        manage: false
      },
      my_target: {
        files: [{
          expand: true,
          cwd: 'assets/js',
          src: '*.js',
          dest: 'min' 
        }]
      },
    },
    less: {
      development: {
        options: {
          compress: true,
          yuicompress: true,
          optimization: 2
        },
        files: {
          "assets/css/styles.css": "assets/less/styles.less" // destination file and source file
        }
      }
    },
    watch: {
      styles: {
        files: ['assets/less/**/*.less', 'assets/js/*.js'], // which files to watch
        tasks: ['less', 'uglify'],
        options: {
          nospawn: true
        }
      }

    }
  });

  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-newer');
  grunt.registerTask('default', ['less', 'watch', 'newer:uglify']);
};

Everything is running fine, but for JS files it's generating the minified version even if the file is not changed.

For example, if I have script1.js, script2.js and script3.js, but only made changes on script1.js - all others will be also generated.

Is there any way to apply the uglify task only if the file has changed? I tried to use grunt-newer but for some reason is not working.

Upvotes: 2

Views: 263

Answers (1)

Victor Monzonis
Victor Monzonis

Reputation: 48

In the initConfig you should use the newer too in the watch settings to call the uglify:

watch: {
  styles: {
    files: ['assets/less/**/*.less', 'assets/js/*.js'], 
    tasks: [**'newer:uglify'**],
    options: {
      nospawn: true
    }
  }

Upvotes: 2

Related Questions