Skip to content

Compiling JavaScript Packages Using Grunt

Franz Noel edited this page Dec 31, 2015 · 7 revisions

Compiling Javascript Packages Using Grunt

This documentation explains how to compile JavaScript codes using npm and grunt

For Java experienced developers: Grunt compiles files, libraries, or packages using JavaScript configuration. In other words, it is similar to Ant, a software that helps compile Java codes before the main Java program runs.

Create a Node Project

  1. Create the folder running mkdir project-name
  2. Run npm init and fill out the name, version, description, entry point, test command, git repository, keywords, author, and license

Install grunt

  1. Run npm install -g grunt-cli to install grunt command line.
  2. Run npm install grunt-contrib-jshint grunt-contrib-nodeunit grunt-contrib-uglify --save-dev to install Grunt plugins in package.json

Create Gruntfile.js

  1. Run vi Gruntfile.js. Then, copy and paste the following codes:

    module.exports = function(grunt) {
      // Project configuration.
      grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        uglify: {
          options: {
            banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
          },
          build: {
            src: 'src/<%= pkg.name %>.js',
            dest: 'build/<%= pkg.name %>.min.js'
          }
        }
      });
    
      // Load the plugin that provides the "uglify" task.
      grunt.loadNpmTasks('grunt-contrib-uglify');
    
      // Default task(s).
      grunt.registerTask('default', ['uglify']);
    };
    
  2. Make sure to save in vi interface by typing :wq!

  3. Run grunt command to minify (or uglify) the source file, based on the configuration.

What's Next

  1. Keep on configuring Gruntfile.js
  2. Keep on running grunt until you get the right results.