Saturday, February 14, 2015

Overview

Grunt is amazing! It automates tasks for you in the most amazing way. It allows you to run tests, minify css/js files, combine js files and much much more.

In this project, I used 2 js files index.js and index2.js. I concatinated them and saved the result to built.js and then I uglified that file and saved the result to built.min.js. I also minimized the css using cssmin.

You can find more information here.

Installation

Step 1

1
2
3
4
5
6
7
8
9
10
### Terminal ###

# Get the right packages
npm install -g grunt-cli

npm install --save-dev load-grunt-tasks
npm install --save-dev grunt-contrib-uglify
npm install --save-dev grunt-contrib-clean
npm install --save-dev grunt-contrib-concat
npm install --save-dev grunt-contrib-cssmin

Step 2

1
2
3
4
### Command Line ###

# Create a Gruntfile.js
touch Gruntfile.js

Step 3

1
2
3
4
5
6
7
8
9
10
11
12
// ### in Gruntfile.js ###

module.exports = function(grunt) {

  require('load-grunt-tasks')(grunt);
  grunt.initConfig({
    // ########## your tasks go here ##############
  });
  
  // now "grunt taskname" will run concat, uglify, some-other-task in that order
  grunt.registerTask('taskname', ['concat', 'uglify', 'some-other-task']);
};

Step 4

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// ### in Gruntfile.js ###

// The initConfig would look something like this
grunt.initConfig({
  concat: {
      dist: {
          src: ['public/javascripts/*.js'],
          dest: 'public/javascripts/built.js',
      },
  },// End concat
  clean: {
      build: {
          src: ["public/javascripts/built.js", "public/javascripts/built.min.js"]
      }
  },// End clean
  uglify: {
      options: {
          mangle: {
              toplevel: true
          },
          compress: true
      },
      my_target: {
          files: {
              'public/javascripts/built.min.js': ["public/javascripts/built.js"]
          }
      }
  },// End uglify
  cssmin: {
      options: {
        files: [{
            expand: true,
            cwd: 'public/stylesheets/',
            src: ['style.css'],
            dest: 'public/stylesheets/',
            ext: '.min.css'
        }]
      }
  }// End cssmin
});

Random Posts