简体   繁体   中英

Grunt watch files created by grunt

I use grunt to automatically create build directory and its content in case any of the source file changes. Now I am trying to watch build directory and copy its content to my project folders whenever some file in build folder changes, however grunts watch will not detect any changes to the files inside build directory, although they are constantly being overwritten. What could be the issue?

My simplified grunt config file to give you an idea:

grunt.initConfig({
    concat:{
        js:{
            files:{
                "build/init.js : ["src/init.js"]
            }
        }
    },
    copy:{
        toproject:{
            expand: true,
            filter: "isFile",
            cwd : "build/",
            src : "*.js",
            dest : "d:/path/to/my/project/js/"
        }
    },
    watch:{
        js:{
            files : ["src/*.js"],
            tasks : ["concat:js"]
        },
        copybuildtoproject:{
            files : ["build/*.js"],
            tasks : ["copy:toproject"]
        }
    }
});

Although init.js is constantly being overwritten in build directory, the copy:toproject will never be fired. I know I could copy the files right when they are concated from src but I need this to work as I explained above instead.

Two possible approaches:

1) rename the watch task, load watch a second time

You could use grunt.renameTask to rename the first watch task, and then load a second copy of watch. It would look something like this:

//from your grunt.initConfig...
watch:{
    js:{
        files : ["src/*.js"],
        tasks : ["concat:js"]
    }
},
watchbuild:{
    copybuildtoproject:{
        files : ["build/*.js"],
        tasks : ["copy:toproject"]
    }
}

// then later...
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.renameTask('watch', 'watchbuild');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('default',['watch','watchbuild']);

2) use grunt-concurrent

A second option is to use the grunt-concurrent plugin. You wouldn't add watch to any tasks, just the concurrent target. In this case, your Gruntfile would resemble this:

grunt.initConfig({
    watch:{
        js:{
            files : ["src/*.js"],
            tasks : ["concat:js"]
        },
        copybuildtoproject:{
            files : ["build/*.js"],
            tasks : ["copy:toproject"]
        }
    },
    concurrent: {
        watch1: ['watch:js'],
        watch2: ['watch:copybuildtoproject']
    }
});

grunt.registerTask('default', ['concurrent:watch1','concurrent:watch2']);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM