Search code examples
gruntjsgroup-concatgrunt-usemin

How to add separator to Concat options when using Usemin


I am using Grunt-usemin. But the concatenated JS is not properly separated by ';'. How do I tell usemin to add the separator only for JS files but not CSS files?

Currently, my usemin tasks look like this:

    useminPrepare: {
        options: {
            dest: '<%= config.dist %>'
        },
        html: '<%= config.app %>/index.html'
    },

    // Performs rewrites based on rev and the useminPrepare configuration
    usemin: {
        options: {
            assetsDirs: ['<%= config.dist %>', '<%= config.dist %>/images']
        },
        concat: {
            separator: ';'
        },
        html: ['<%= config.dist %>/{,*/}*.html'],
        css: ['<%= config.dist %>/styles/{,*/}*.css']
    },

Another use case would be wrapping each concatenated module in an IIFE, which requires this configuration, but should only be applied to *.js files:

concat: {
    options: {
        banner: ';(function () {',
        separator: '})(); (function () {',
        footer: '})();'
    }
}

Solution

  •  concat: {
      options: {
        process: function (src, filepath) {
          if (filepath.split(/\./).pop() === 'js') {
            return src + ';\n';
          }
          return src;
        }
      }
    }
    

    Explanation of the process option link

    The function splits the filepath into an Array with . (dot) as a separator. The pop() method from Array returns the last item of the array which should be the extension.