Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I'm trying out Grunt and need a simple way to concatenate my modules

This is my first time using Grunt and I'd like to have it combine all my js modules, each of which is wrapped in an immediately executing function, containing a 'use strict' declaration and put them into one file, wrapped up in only one immediately executing function, with only one 'use strict' declaration.

How is this normally done?

I figured this would be a common use case? Perhaps I'm going about things the wrong way? Should I be using one of the module loading formats (i.e. commonjs, amd) All these files will always be loaded together in the browser, so I actually wouldn't mind removing all the immediately executing functions if that's how people normally go about it. The important part is that the end result is somehow wrapped, passes lint and unit tests and contains the 'use strict' declaration.

(I should clarify, I do have it working, linting, unit-testing, concatenating, and minifying, it just feels like I'm doing something wrong when I see a bunch of unnecessary immediately executing functions in the final concatenated file.)

like image 398
GxXc Avatar asked Oct 16 '12 04:10

GxXc


2 Answers

As of pull request 10, grunt-contrib-concat now has a footer option. Instead of an intro and an outro file, I would use a banner and a footer.

Gruntfile.js

concat: {
  dist: {
    src: ['src/my-lib.js'],
    dest: 'dist/<%= pkg.name %>.js',
    options: {
      banner: ";(function( window, undefined ){ \n 'use strict';",
      footer: "}( window ));"
    }
  }
}

In my opinion, this is more maintainable and allows for templating using other properties defined in your Gruntfile.

like image 102
briangonzalez Avatar answered Oct 22 '22 07:10

briangonzalez


I usually do it like the jQuery team does it. You create an intro.js and outro.js and put everything else in between:

intro.js

;(function( window, undefined ){
  'use strict';

outro.js

}( window ));

grunt.js:

concat: {
  dist: {
    src: [
      'js/src/intro.js',
      ...
      'js/src/outro.js'
    ],
    dest: 'js/out/app.js'
  }
}
like image 27
elclanrs Avatar answered Oct 22 '22 07:10

elclanrs