Making life easier, GruntJS (for beginners)

What is GruntJS


Most JS developers already use some kind of build tools for their development, even if they don’t know or do not use this term. They combine files during development, reduce JavaScript code to speed up page loading and convert Sass, or reduce the number of files in CSS for the browser, and much more. Most often these are different tools, which is not very convenient.

Grunt helps you manage all of these steps in one place and organize third-party components.

And why do we need this happiness?


All previously existing tools had their own foundations in various areas of programming. Since they were not built primarily for JS developers, they had their pros and cons. Some require knowledge of other languages ​​or use separate XML dialects that you need to learn first, and then they are not so easy to configure.
So why not have a tool that is specifically designed for this, that is written in a language that JS developers use daily, which makes using it simple for them? Grunt is completely written in JavaScript and runs on Node.js, it can be used on various platforms.

I hope to put nodejs, it will not be difficult. One remark on this for windows users: to use the command line to the full extent to control nodejs and its packages, I advise you to put https://code.google.com/p/msysgit/ .

Grunt is still young, but has already undergone some significant changes in the recently released version 0.4. Now it consists only of a small command line client and showing the main task. All additional functions are based on plugins, so you can customize it for the special needs of your project without any frills. Grunt and all plug-ins are added to your project directory to make sure that everything you need to build and maintain your project always remains in place. These modules can either be downloaded along with the project, or if the development platforms are different, it is better to store all the modules used in a file, file ground (more on that later).

Despite the fact that Grunt is still pretty early on, there are already many plugins for (almost) all your development needs:

Reducing JavaScript and CSS, integrating CSS and JavaScript preprocessors such as Sass / Compass, Less and Stylus, CoffeeScript or LiveScript Sass / Compass, optimizing PNG and JPEG image file sizes and automatically embedding images, and much more.

If you plan on writing large web applications, Grunt also integrates optimizations for Require.js and the Google Closure Compiler and allows you to pre-compile Handlebars, Jade, Underscore, Mustache, Eco or Hogan templates. There are already plugins for the most common testing frameworks such as Jasmine, Mocha, QUnit, and Cucumber.
All available plugins have links on the Grunt website (and if someone publishes a new Node.js module with the keyword "gruntplugin", it is automatically added to the list).
As you can see, Grunt will not only help you create your own project, but also acts as a central tuning node for external tools.

Installation and preparation for work


Now you have a first impression of what Grunt is, and it's time to start. First of all, make sure Node.js is installed on your computer. There are installers available for various platforms that let you get started right away. Open a terminal and type
npm install grunt-cli -g
to install the grunt command line tool.

Older versions of Grunt came with a set of predefined core tasks. In order to make it more flexible and customizable, they were removed in the recent 0.4 release and can be installed as separate task plugins that will make it easier for you to start working with it.

First, create a file in the project root folder called package.json. If you are familiar with Node.js, you may already be familiar with this file, we will start with the most basic for our project.

{
	"author"	: "authorName",
	"name"		: "FrontEnd-Project",
	"version"	: "0.0.1",
	"devDependencies" : {
		"grunt"					: ">= 0.4",
		"grunt-cli"				: ">= 0.1.6",
		"grunt-contrib-watch"	: "~0.3.1",
		"grunt-contrib-cssmin"	: ">=0.5.0",
		"grunt-contrib-uglify"	: ">=0.2.0",
		"grunt-contrib-concat"	: ">=0.1.3"
	}
}

(package.json is the settings file for nodejs. We put the file in the root of the project folder, open the console, go to the folder and execute npm install, all the packages and dependencies described in the file will be installed in your project folder. More details http: // package .json.nodejitsu.com / ).

Launch Grunt

After Grunt and all the dependencies necessary for our project are installed, it is time to start with the configuration of Grunt itself. Thus, we add a file called Gruntfile.js to the root of our project, next to the previously created package.json file. This is the main file for the Grunt configuration, which contains a list of downloadable tasks, and a description of their work.

The main configuration file may look like this:

//Стандартный экспорт модуля в nodejs
module.exports = function(grunt) {
  // Инициализация конфига GruntJS
  grunt.initConfig({
    //Настройки различных модулей GruntJS, их нужно предварительно установить через менеджер пакетов npm, или добавить в файл package.json перед запуском npm install
    //Например проверка кода javascript с помощью утилиты jshint
    jshint: {},
    //Склеивание файлов
    concat: {}
    //И так далее
  });
  //Загрузка модулей, которые предварительно установлены
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-concat');
  //Эти задания будут выполнятся сразу же когда вы в консоли напечатание grunt, и нажмете Enter
  grunt.registerTask('default', ['jshint', 'concat']);
};

So, you see that all the necessary configurations are written in JavaScript. Basically, you need three different methods for working with Grunt:

grunt.initConfig
grunt.loadNpmTasks
grunt.registerTask

Each task can be called separately from the command line, passing its name as a command line parameter: For example, grunt jshint will only perform tasks aimed at controlling the programming style to meet the standards of your project. With grunt.registerTask, you define a default task to run when Grunt is called without parameters. It performs the listed tasks in the given order, in our case jshint, concat and uglify.

Describe each plugin is a separate topic for conversation. Often used can be found here https://github.com/gruntjs/grunt-contrib . There you can find a full description and the latest version for commonly used GruntJS plugins.

Well, finally!


To start using Grunt we will do the following steps:
  1. You need to install nodejs, you can find the installer for your system here http://nodejs.org/
  2. If you have windows, I recommend installing https://code.google.com/p/msysgit/ for convenience.
  3. We create two package.json and Grunfile.js files in the project folder, configure them, and read how to do this.
  4. We create a folder for the project, or go to an existing one using the console, and execute the npm install command in order to install Grunt, and all the necessary packages (which are described previously in package.json).
  5. Well, to launch Grunt, we execute the grunt command in the console.


With Grunt, JS developers have a very flexible tool at hand to help automate repetitive tasks. Once set up, you can set up timed tasks, do this magic in the background, or integrate Grunt into your IDE or coding editor as an external development team (which works great in Sublime Text, for example).

Verification and testing code improves overall quality and helps you maintain a consistent coding standard, which makes Grunt an ideal tool for teams working on large-scale projects.

Official site http://gruntjs.com/

Thank you for your attention, see you soon.

Also popular now: