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

泪湿孤枕 提交于 2019-11-30 11:48:43
elclanrs

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'
  }
}

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.

Dmitry Pashkevich

Just want to add to @elclanrs answer that if you want to be able to keep your modules in separate files for easier debugging during development, you would obviously have to wrap them with intro.js and outro.js as well. Using the built-in concat task you'd have to write something like:

concat: {
  events_debug: { // wrap the 'events' module in IIFE
    src: [
      'js/src/intro.js',
      'js/src/events.js',
      'js/src/outro.js'
    ],
    dest: 'js/out/events.js'
  },
  callbacks_debug: { // wrap the 'callbacks' module in IIFE
    src: [
      'js/src/intro.js',
      'js/src/callbacks.js',
      'js/src/outro.js'
    ],
    dest: 'js/out/callbacks.js'
  }

  // zzZZZ...
}

Which is very tedious and self-repeating. Perhaps you may want to create a custom task for mass-wrapping files, e.g.

wrap: {
    html: {
        intro: 'partials/intro.js',
        outro: 'partials/outro.js',
        src: 'js/*.js',
        dest: 'out' // output directory
    }
}

There was a question about this recently, see this thread:

Using grunt concat, how would I automate the concatenation of the same file to many other files?

I would recommend you to use my grunt plugin grunt-concat-deps since it automatically resolves your modules independent on your architecture.

PLUS: You don't need any explicit module configuration for the plugin as it relies on declarative and decentralized module definition in a YUIDoc style.

See here for further information: https://github.com/leoselig/grunt-concat-deps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!