Search code examples
javascriptgrunt-contrib-concat

How to remove (function(){'use strict'; } and ()); when concatenating with grunt-contrib-concat


I can concatenate my files in the proper order and I can add (function(){'use strict'; to the top and }()); to the bottom of the output file but I don't know how to remove the (function(){'use strict'; and }()); from the individual files before concatenating.

I read through the docs and I tried using the custom process example and I know I need to make some changes to this line src.replace(/(^|\n)[ \t]*('use strict'|"use strict");?\s*/g, '$1'); but unfortunately I don't understand that line or how to change it.

Lastly, I don't know if it even matters to make this change. When I concat and minify my code, leave it as is, and don't add the banner and footer everything works fine. Is there any benefit to replacing the individual use-stricts with just the one?

From my Gruntfile

concat: {
    options: {
        banner: "(function(){'use strict';\n",
        footer: '}());',
        process: function(src, filepath) {
            return '// Source: ' + filepath + '\n' +
                src.replace(/(^|\n)[ \t]*('use strict'|"use strict");?\s*/g, '$1');
        }
    },
    nonMin: {
        src: ['src/angular-gmap-gplace.js', 'src/modules/*.js'],
        dest: 'dist/angular-gmap-gplace.js'
    },
    min: {
        src: ['src/**/*.js'],
        dest: '.tmp/concat.js'
    }
}

Solution

  • Is there any benefit to replacing the individual use-stricts with just the one?

    No. There are only drawbacks.

    Using an IIFE in each file means that each file has it's own scope and, unless you deliberately create a global, can't interfere with the other files.

    If you merge them into a single IIFE then that is no longer true, and they share their scopes with each other. You risk accidentally overwriting a variable used by one with file an identically named variable in a different file.