Bootstrap 4 – JavaScript file concatenation

ASP.NET Core MVC Web Application Project Structure” href=”” target=”_blank”>ASP.NET Core MVC Web Application Project Structure

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 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 G runt build task to run the appropriate tasks to create and populate the dist directory. You should also create a G runt 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.

Comments are closed.