Menu

Rename Copied Files Using Grunt Plugin grunt-contrib-copy

March 4, 2015 by Christopher Sherman

Grunt’s copy plugin, grunt-contrib-copy, comes in quite handy for tasks like copying CSS and JavaScript from a Bower components folder to a friendly css/ or js/ directory. In this tutorial, I’ll show you how to extend copy tasks to rename files in the destination folder.

My desire to rename copied files began with wanting to use the slick.js carousel. I installed the slick library via the Bower package manager, it arrived in my bower_components folder, and everything looked good. My plan was to compile slick into a larger CSS file, treating its files as partial Sass files. The problem was, the files didn’t have the leading underscore convention (_partial.scss) to indicate they should be treated as partials.

Luckily, Grunt has a built-in rename function in the options object which you can find hidden in the Gruntfile documentation. Using this function, I’m able to intercept the destination directory and source path, check if the Sass file has a leading underscore, and append one if not. Check out my copy task below.

copy: {
styles: {
// SCSS.
expand: true,
flatten: true,
cwd: 'bower_components/slick.js',
src: ['**/*.scss'],
dest: '../scss/slick/',

    /* Rename the SCSS file to include
        * the underscore naming convention.
        */
    rename: function (dest, matchedSrcPath) {
        /* Check if the Sass file has a
            * leading underscore.
            */
        if (matchedSrcPath.substring(0, 1) !== '_') {
            return dest + '_' + matchedSrcPath;
        }
    },

},
},

Grunt Optimization