3

我的 Gruntfile.js 中有以下配置:问题是,当某些文件被更改时,'uglify' 任务对所有文件都照常执行。我做错了什么?

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']);
};
4

2 回答 2

3

默认情况下,监视任务将产生任务运行。因此它们处于不同的进程上下文中,因此在监视事件上设置配置将不起作用。您需要启用nospawn不产生任务运行并保持在相同的上下文中:

watch: {
  options: { nospawn: true },
  scripts: {
    files: ['js/**/*.js'],
    tasks: ['uglify']
  }
},
于 2013-06-03T03:47:16.190 回答
1

你快到了。你的“ onWatch ”函数应该是这样的:

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);
});

注意nospawn:true在您的 wact 任务选项中也是强制性的。

于 2014-02-21T20:45:57.873 回答