Optimizing Your Website with Bootstrap: JavaScript file concatenation

Just as we minified and concatenated our style sheets, we shall now go ahead and minify and concatenate our JavaScript files. Go ahead and take a look at grunt-contrib-uglify. Visit https://github.com/gruntjs/grunt-contrib-uglify for more information.

Install this by typing the following:

npm install grunt-contrib-uglify -save-dev

Then, as always, enable it by adding grunt.loadNpmTasks(‘grunt-contrib- uglify’) ; to our Gruntfile.js. Next, create a new task:

“uglify”: {

“target”: {

“files”: {

“dist/js/myphoto.min.js”:  [“src/js/*.js”]




Running grunt uglify should produce the following output:

Figure 8.8: The console output after running the uglify task

The dist/js folder should now contain a file called myphoto.min.js. Open it and verify that the JavaScript code has been minified. As a next step, we need to be sure that our minified JavaScript file will actually be used by our production-ready index.html. We will use grunt-processhtml, which we installed in the previous section. All that we need to do is wrap our link tags inside a special build comment—<! — build:js js/myphoto.min.js ->:

<!— build:js js/myphoto.min.js —>

<script src=”js/alert.js”></script>

<script src=”js/carousel.js”></script>

<script src=”js/a11yhcm.js”></script>

<!— /build ->

Next, we will add our uglify task to our watch task list:

“watch”: {

“target”: {

“files”: [“src/styles/myphoto.css”],

“tasks”: [“uncss”, “cssmin”, “processhtml”, “uglify”,




Golden rules when working with Grunt

When developing a Grunt file (or any build file for that matter), there are a few practices that you should keep in mind:

  • The dist folder should not contain any unprocessed source files, src is the “unprocessed” code, and dist is the result of “processing” src to create a distributable.
  • Typically, you should create a Grunt build task to run the appropriate tasks to create and populate the dist directory. You should also create a Grunt serve task to run the appropriate tasks for a development server, with the watch task being the final task that is run.
  • The watch task should be watching all source files. In our case, we watched just one, in order to keep the example simple and easy to understand.

Source: Jakobus Benjamin, Marah Jason (2018), Mastering Bootstrap 4: Master the latest version of Bootstrap 4 to build highly customized responsive web apps, Packt Publishing; 2nd Revised edition.

Leave a Reply

Your email address will not be published. Required fields are marked *