javascriptgruntjsgrunt-contrib-uglify

How to grunt-uglify multiple script files while keeping folder structure


I have not found a good way to grunt-uglify multiple script files spread over multiple folders while keeping the folder structure including the uglified files intact. The only reason I want to do this is to be able to increase the performance of the "legacy" part of the web page I'm working on.

I have found a way around this which I don't want to do, since it will take to much time, and that is to do it like in this answer (they specify each 'src' and 'dest' pair separately): How to configure Grunt to minify files separately

An example of what I want to achieve:

**Source directory (no uglify applied):**
src
 |- app1
    |- randomFile.js
    |- scripts
       |- file1.js
       |- file2.js
    |- libs
       |- file3.js
       |- file4.js
 |- app2
   |- scripts
       |- file1.js
       |- file2.js

**Destination directory (uglify applied, and the same file name):**
dist
 |- app1
    |- randomFile.js
    |- scripts
       |- file1.js
       |- file2.js
    |- libs
       |- file3.js
       |- file4.js
 |- app2
    |- scripts
       |- file1.js
       |- file2.js

Btw, I want to do the same for CSS files if possible.

Is this possible?


Solution

  • The principle in Rafa Heringer's answer on the post you linked to looks promising, with a little twist:

    uglify: {
        min: {
            files: grunt.file.expandMapping(['path/**/*.js', 'path2/**/*.js'], 'destination/', {
                rename: function(destBase, destPath) {
                    return destBase+destPath.replace('.js', '.min.js');
                }
            })
        }
    }
    

    The only difference here is the double asterisk between the base path and the wildcard filename with its extension. That will go through all the subfolders and, hopefully, output each find it finds in its rightful folder.

    The output would be:

    path/test.js => destination/path/test.min.js
    path/subpath1/abc.js => destination/path/subpath1/abc.min.js
    path/subpath2/yey.js => destination/path/subpath2/yey.min.js
    path2/foo.js => destination/path2/foo.min.js
    

    When it comes to doing the same with CSS (using the grunt-contrib-cssmin plugin), the approach mentioned above would still work, but you would have to combine it with the relevant plugin configurations that must be in place to output minified CSS content the way you want.

    PS: I haven't tried running it myself!