Search code examples
gruntjsuglifyjs2

Setting the destination folder with uglify in Grunt


With the Grunt code and folder structure as can be seen below, when I run grunt uglify , the result is that the output creates subfolder structure \js\src within \min folder, where the deepest folder (src) will contain the minified files. But I want the minified files to be created in the \min folder root.

If I set the dest parameter value to empty:``, the files are created in the same folder as the src folder.

If I set the dest parameter value to :/ or /js/min or /js/min/, nothing is created.

How can I generate the minified files directly in the root of the min folder?

module.exports = function(grunt){ // 1

grunt.initConfig({
  uglify: {
    my_target: {
      files: [{
          expand: true,
          src: 'js/src/*.js',
          dest: 'js/min/',
          ext : '.min.js',
      }]
    }
  }
});

  grunt.loadNpmTasks('grunt-contrib-uglify'); //https://www.npmjs.com/package/grunt-contrib-uglify


  grunt.registerTask('default', function() { // 4
      grunt.log.writeln('Hello, from the default grunt task!'); // 5
  });

}

enter image description here


Solution

  • The Grunt documentation has a relevant section about building the files object dynamically.

    Of particular interest is the "cwd" property:

    All src matches are relative to (but don't include) this path.

    This will allow us to remove the unwanted path from our "src" value by setting it as the value of "cwd". This will mean that the generated source file paths will not have the unwanted prefix ("/js/src/") when they are added to the /js/min folder.

    Our resulting Grunt file looks as follows:

    module.exports = function (grunt) {
    
        grunt.initConfig({
            uglify: {
                my_target: {
                    files: [{
                        expand: true,
                        cwd: 'js/src/',
                        src: '*.js',
                        dest: 'js/min/',
                        ext : '.min.js',
                    }]
                }
            }
        });
    
        grunt.loadNpmTasks('grunt-contrib-uglify');
    
        grunt.registerTask('default', ['uglify']);
    
    };