Tips & Tricks

Build project with Grunt

  - 3 min read
Build project with Grunt

I use Grunt in development stage, but it can also be used to build the finished project for production. Here is a project example using Grunt to create the build. List of Grunt plugins:

1. Minify CSS

The plugin grunt-contrib-cssmin is used to minify the CSS files to reduce the files size and concatenate this files into a single file style.min.css to reduce the number of http requests.

"cssmin": {
  "combine": {
    "files": {
      "build/css/style.min.css": [
        "public/lib/bootstrap-css/css/bootstrap.min.css",
         "public/lib/fontawesome/css/font-awesome.min.css",
         "public/css/style.css"
      ]
    }
  }
}

2. Compress JavaScript

The plugin grunt-contrib-uglify is used to compress and concatenate multiple JavaScrit files.

Notice in development stage the file google-analytcis.js is not integrated in index.html page while this file in needed only in production.

"uglify": {
  "dist": {
    "options": {
      "mangle": true
    },
    "files": [
      {
        "build/js/script.min.js": [
            "public/js/script.js",
            "public/js/google-analytics.js"
        ]
      }
    ]
  }
}

3. Process HTML file

The plugin grunt-processhtml is used to change the integrated CSS & JavaScript files in index.html

The CSS files are replaced with style.min.css and the JavaScript files with script.min.js file.

Notice that the file livereload.js is used only in development and has to be removed in production.

 

<!-- build:css css/style.min.css -->
<link rel="stylesheet" href="lib/bootstrap-css/css/bootstrap.min.css"/>
<link rel="stylesheet" href="lib/fontawesome/css/font-awesome.min.css"/>
<link rel="stylesheet" href="css/style.css"/>
<!-- /build -->
<!-- build:js js/script.min.js -->
<script src="js/script.js"></script>
<!-- /build -->
<!-- build:remove -->
<script src="http://localhost:35729/livereload.js"></script>
<!-- /build -->

4. Copy files

The plugin grunt-npmcopy is used to copy fontawesome font files and the custom font used in style.css

"npmcopy": {
  "fontawesome": {
    "options": {
      "srcPrefix": ""
    },
    "files": {
      "build/fonts": "public/lib/fontawesome/fonts/*"
    }
  },
  "customfonts": {
    "options": {
      "srcPrefix": ""
    },
    "files": {
      "build/fonts": "public/fonts/*"
    }
  }
}

5. Replace text

The plugin grunt-text-replace can be used to replace text in any files.

In this example snippet I change any value of example.dev in the file index.html to ismaail.com

"replace": {
  "html": {
    "src": "build/index.html",
    "dest": "build/index.html",
    "replacements": [{
      "from": "example.dev",
      "to": "ismaail.com"
    }]
  }
}

Finale step

To create the build folder, in the project folder run the command grunt build,

now the project is ready for production.

Copyright © - 2013 ismaail.com. All rights reserved.