I have following config in my Gruntfile.js: Problem is, that when some file is changed, 'uglify' task is performing as usual for all files. What I am doing wrong?
module.exports = function(grunt) {
grunt.initConfig({
pkg : grunt.file.readJSON('package.json'),
watch: {
scripts: {
files: ['js/**/*.js'],
tasks: ['uglify']
}
},
uglify : {
options: {
banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n',
sourceMapRoot: 'www/js/sourcemap/'
},
build: {
files: [
{
expand: true,
cwd: 'js/',
src: ['**/*.js', '!**/unused/**'],
dest: 'www/js/',
ext: '.js'
}
]
}
}
});
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.event.on('watch', function(action, filepath) {
grunt.config(['uglify', 'build', 'src'], filepath);
});
grunt.registerTask('default', ['uglify', 'watch']);
};
By default the watch task will spawn task runs. Thus they are in a different process context so setting the config on the watch event wont work. You'll need to enable nospawn to not spawn task runs and stay within the same context:
watch: {
options: { nospawn: true },
scripts: {
files: ['js/**/*.js'],
tasks: ['uglify']
}
},
You were almost there. Your "onWatch" function should look something like this :
grunt.event.on('watch', function(action, filepath, target) {
grunt.config('uglify.build.files.src', new Array(filepath) );
// eventually you might want to change your destination file name
var destFilePath = filepath.replace(/(.+)\.js$/, 'js-min/$1.js');
grunt.config('uglify.build.files.dest', destFilePath);
});
Note nospawn:true in your wacth task options is mandatory too.