How can I rename files with Grunt, based on the respective file's parent folder name?

前端 未结 5 687
借酒劲吻你
借酒劲吻你 2021-01-30 10:28

I have a the following structure:

src/
    modules/
        module1/
            js/
                main.js
            scss/
                main.scss
                 


        
5条回答
  •  别那么骄傲
    2021-01-30 11:18

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

提交回复
热议问题