eran otzap
eran otzap

Reputation: 12533

Concat javascript files under a single file

File structure.

/app 
  /components 
     /core 
        /extensions
           - array.js 
           - string.js
        /services
           - logger.js 
        /lib 
           - core.js 

Core.js

(function() {
     'use strict';
     angular.module('app.core',[]);  
}());

What i need is to overwrite core.js on each build by copying all the other js files in that folder on to it, while keeping this first original content of the module deceleration.

This is the wanted result for Core.js :

(function() {
     'use strict';
     angular.module('app.core',[]);  
}());
// content of array.js
(function() {
   'use strict';

    var core = angular.module('app.core');
    core.config( .....) 
 }());     

 // content of string.js
 ...
 // content of logger.js

Iv'e tried 2 grunt tasks which i believed where men't for this purpose but did not find a way the configure them to my needs.

1) grunt-concat had 2 issues the first that it appends the contents from the start of the file and not the end of the file like i wanted. and it does not override the existing content.

2) grunt-copy does override but it overrides the entire file.

What iv'e attempted is to use the process function for grunt copy.

  copy: {
      src: ['app/components/core/{,*/}*.js'],
      dest: 'app/components/core/lib/core.js',
      options:{
          process : function(content, srcpath){
              return content; // do some manipulation on content here. 
          }
      }         
  }

This is also problematic since i would have to keep the text that comprises the angular module definition in my Gruntfile and append it to the first content that comes into my process function, something like this which seems really messy.

 process : function(content, srcpath){
              if(isFirst) {
                  isFirst = false;
                  // here i will append the angular module deceleration. 
              }
              return content;
          }

Is there an elegant way to achieve what iv'e described ?

Upvotes: 0

Views: 538

Answers (1)

Xavier Priour
Xavier Priour

Reputation: 2121

grunt-contrib-concat is exactly what you need, just do the following:

  1. rename your current core.js to _banner.js (or anything you like) - it's a good practice to not overwrite your banner file anyway
  2. setup concat to agregate _banner.js then your other files, and save it as core.js:

    concat: {
      core: {
        files: [{
          src: [
            'app/components/core/_banner.js',
            'app/components/core/extensions/*.js',
            'app/components/core/services/*.js'
          ],
          dest: 'app/components/core/lib/core.js'
        }]
      },
    },
    

Should give you what you want

Upvotes: 1

Related Questions