Use Grunt and Uglifyjs to combine multiple javascript files into a single javascript file

Posted by: Seth Lakowske

When you are ready to publish your new JavaScript project, you can combine your JavaScript files into one file to get faster page downloads, fewer GET requests and lower complexity for users to manage.  Users may import your project more easily with a single script tag rather than many script tags.

npm install grunt-contrib-uglify

Here is a simple configuration that generates a single JavaScript file from three source files. Note that we generate a source map that is used to debug the JavaScript file in the browser.  The source map will map code from our single script to the individual files so you can track down bugs more easily.

// Sample project configuration.
grunt.initConfig({
  uglify: {
    my_target : {
      options : {
        sourceMap : true,
        sourceMapName : 'sourceMap.map'
      },
      files : {
        'composite.min.js' : ['src/Model/Mux.js', 'src/Model/Hasher.js', 'src/Model/Cloner.js']
      }
    }
  }
});

Here is an example of minifying all JavaScript files in my projects src/ directory.

// Combine all files in src/
grunt.initConfig({
  uglify: {
    all_src : {
      options : {
        sourceMap : true,
        sourceMapName : 'sourceMap.map'
      },
      src : 'src/**/*.js',
      dest : 'composite.all.min.js'
    }
  }
});

You can include your combined JavaScript file (composite.all.min.js) in a HTML page using the <script> tag.  Because you created a source map, when you open the debugger, you will see a list of individual files rather than a single unintelligible combined file.

Also note, if you’re starting a fresh project and like or are interested in Node.js on the backend, you may be interested in Browserify, which lets you write Node.js style modules in browser.  Combining them into a single Javascript file is possible too.  To learn more about this style of Javascript development, checkout the Browserify Tutorial.  It may be the direction you want to head towards in the future.

Citations:

https://github.com/gruntjs/grunt-contrib-uglify

https://github.com/gruntjs/grunt-contrib-uglify/issues/23