Grunt:如何仅为修改后的文件运行任务?

时间:2016-03-29 15:07:59

标签: javascript node.js gruntjs

我有以下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']);
};

一切运行正常,但对于JS文件,即使文件未更改,它也会生成缩小版本。

例如,如果我有script1.jsscript2.jsscript3.js,但只对script1.js进行了更改 - 其他所有内容也会生成。

只有在文件发生变化时才有办法应用uglify任务吗?我尝试使用grunt-newer但由于某种原因无效。

1 个答案:

答案 0 :(得分:1)

在initConfig中,你应该在监视设置中使用 newer 来调用uglify:

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