Menu

Copy File If It Doesn't Exist with Grunt Plugin grunt-contrib-copy

March 5, 2015 by Christopher Sherman

Grunt’s copy plugin, grunt-contrib-copy, is helpful for tasks like copying CSS and JavaScript from a Bower components folder to a friendly directory. Copying files is problematic, however, when you’ve modified the destination files and don’t want your changes overwritten the next time the copy task runs. In this tutorial I’ll explain how to add a filter to the copy task to ignore files that already exist.

The filter function below makes use of the NPM Path module to construct the destination file path. Check out the documentation for the Path module to customize the filter for your needs.

copy: {
main: {
// Vendor scripts.
expand: true,
cwd: 'bower_components/',
src: ['**/*.js'],
dest: '../scripts/'

    // Copy if file does not exist.
    filter: function (filepath) {
        // NPM load file path module.
        var path = require('path');

        // Construct the destination file path.
        var dest = path.join(
            grunt.config('copy.main.dest'),
            path.basename(filepath)
        );

        // Return false if the file exists.
        return !(grunt.file.exists(dest));
    },

},
},

Grunt Optimization