How can I rename files with Grunt, based on the respective file's parent folder name?
Solution 1:
This can be done using the grunt-contrib-copy plugin.
The main thing to note is that you can change the destination programmatically by using a rename function (which takes in the destination and source of each file).
Here is a (somewhat brittle) sample Gruntfile.js
that should copy to your desired structure:
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
copy: {
main: {
files: [
{
expand: true,
cwd: 'src/modules/',
src: ['**/*.js'],
dest: 'dev/js/',
rename: function(dest, src) {
// use the source directory to create the file
// example with your directory structure
// dest = 'dev/js/'
// src = 'module1/js/main.js'
return dest + src.substring(0, src.indexOf('/')) + '.js';
}
},
{
expand: true,
cwd: 'src/modules/',
src: ['**/*.scss'],
dest: 'dev/css/',
rename: function(dest, src) {
return dest + src.substring(0, src.indexOf('/')) + '.css';
}
},
{
expand: true,
cwd: 'src/modules/',
src: ['**/*.html'],
dest: 'dev/',
rename: function(dest, src) {
return dest + src.substring(0, src.indexOf('/')) + '.html';
}
}
]
}
}
});
grunt.loadNpmTasks('grunt-contrib-copy');
// Default task(s).
grunt.registerTask('default', ['copy']);
};
Solution 2:
There's no need to use grunt-contrib-copy
just for this any more, you can now take advantage of grunt.file.expandMapping
which has options to just change the file extension, or to define a function that returns the output filename.
Here's an example of a files
object in a jade
task for compiling .jade templates into .html files:
files: [{
expand: true,
src: "**/*.jade",
dest: "<%= distDir %>",
cwd: "<%= assetsDir %>/jade",
rename: function(dest, matchedSrcPath, options) {
// return the destination path and filename:
return (dest + matchedSrcPath).replace('.jade', '.html');
}
}]
It would have been easier to use the ext: '.html'
option instead of the rename
option in this case, but I'm using rename
here so you can see how it works.
More info about the ext
and rename
(and other) options in the grunt.file docs. Some more examples here and here.
Solution 3:
You could simply use the options: expand : true, flatten: true
No need for custom rename callbacks.