如果启用了Uglify中的动态扩展,如何仅使用Grunt.js监视任务来更改文件?

时间:2013-05-30 12:23:27

标签: node.js gruntjs watch uglifyjs

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

2 个答案:

答案 0 :(得分:3)

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

watch: {
  options: { nospawn: true },
  scripts: {
    files: ['js/**/*.js'],
    tasks: ['uglify']
  }
},

答案 1 :(得分: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);
});

注意您的wacth任务选项中的nospawn:true也是必需的。