Introduction
Grunt is a tool written in Node.js, therefore before installing Grunt it is necessary to install Node.js and its package manager npm. If they are already installed, it is necessary to check whether they are up-to-date versions and, if necessary, do their update. Since one of Grunt’s frequent tasks is to compile SASS to CSS, you need to have SASS installed. All these installations are explained in the article Install tools for web development
Npm and initial package.json
Package.json is used by npm because it stores meta data related to modules installed by npm within a project. Inside the file there is a list and map with project dependencies (dependecies or devDependecies) that can be downloaded. We hereby make it easier for someone who will use our project to download them only if they need them.
For local installation, we need to set the path in the command line to the local selected folder where we will create the grunt project. Next, we issue a command that creates a base package.json file:
npm init
After starting the command in the command prompt, the application asks to fill in the questions needed to create the package.json file, such as:
- name
- version
- description
- keywords
- …
See more about padding here
Grunt installation
Global installation of Grunt
Grunt is installed from the command line with the command:
npm update -g grunt
Interface installation
The task of the interface is to load a local installation of the Grunt library and apply configuration from the local Gruntfile to perform the tasks requested of it
Installing the command line interface so called. grunt-CLI command:
npm install -g grunt-cli
Local installation of Grunt
npm install grunt –save-dev
Installation of Grunt plugin
Pre-prepared functionalities are usually added to Grunt via plugins. When installing the plugin, there are two options for saving dependencies as:
- dependeces
are dependencies that are always downloaded with your module - devDependeces
are dependencies used only during development. When we put a dependency in devDependeces, we can prevent the end user from downloading these dependencies that are only used during module development. If we want the plugin to be like a development expense, then during installation we add the extension “-dev” to the command.
When installing the plugin, the corresponding record is automatically added to the package.json file. Depending on whether we used the “-dev” extension or not, the record will be saved either in the “dependeces” or “devDependencies” section.
You can find a list and search of all available grunt plugins on the official site. or list with a simple command:
npm search grunt
The most commonly used grunt plugins are:
- npm install grunt-contrib-sass –save-dev – compiles SASS to CSS very quickly
- npm install grunt-postcss –save-dev
It consists of three parts:- Autoprefixer
- pixrem (switches rem to px for older browsers)
- cssnano (for minification)
- npm install grunt-contrib-concat –save-dev – concatenate multiple (css or js) files
- npm install grunt-contrib-clean –save-dev – delete tasks
- npm install grunt-contrib-imagemin –save-dev – optimize images
- npm install grunt-contrib-uglify –save-dev – “saves” javascript code for production
- npm install grunt-contrib-jshint –save-dev – validate javascript
- npm install grunt-contrib-watch –save-dev – watch for file changes and run tasks
Commands with the suffix ” -dev ” indicate that dependencies will be used during project development (ie development) and will appear in the package.json file under “devDependencies”!
Example
When installing local dev-dependencies via plugins, automatically its code is filled in the package.json file, which after installation can look like this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
{ "name": "my-project", "version": "0.0.1", "description": "My project" "devDependencies": { "grunt": "^0.4.5", "grunt-concurrent": "^1.0.0", "grunt-contrib-clean": "^0.6.0", "grunt-contrib-imagemin": "^0.8.1", "grunt-contrib-jshint": "^0.10.0", "grunt-contrib-uglify": "^0.6.0", "grunt-contrib-watch": "^0.6.1", "grunt-sass": "^0.16.1", "load-grunt-config": "^0.13.1" }, "dependencies": { "jshint-stylish": "^1.0.0", "time-grunt": "^1.0.0" } } |
Defining Grunt features (gruntfile.js)
When we define the dependencies in the package.json file, we will be able to call them within the Gruntfile with simple commands. Creating Gruntfile.js starts by creating the file itself in the root of our project and inserting the initial code:
|
1 2 3 4 5 6 |
module.exports = function(grunt) { // orders are placed here // which activate dependencies registered in package.json }; |
Each task we want to add must first be pre-installed as dependencies in package.json.
Grunt object properties
-
InitConfig
123grunt.initConfig({// Code goes here to define the properties of each plugin});This property is used to configure properties of the plugin. The explanation of how to define the properties related to the application of each plugin is most often explained through examples on the official pages of the plugins:
- grunt-contrib-sass – compiles SASS to CSS very fast
- grunt-postcss – autoprefixer + pixrem + cssnano
- grunt-contrib-concat – concatenate multiple (css or js) files
- grunt-contrib-clean – clears tasks
- grunt-contrib-imagemin – optimizes images
- grunt-contrib-uglify – “grunts” javascript code for production
- grunt-contrib-jshint – validate javascript
- grunt-contrib-watch – watch for file changes and run tasks
Example
12345678910111213grunt.initConfig({uglify: {options: {mangle:true,compress:true,sourceMap:"dest/aplication.map"banner:"/* My Ugly Code*/n},target : {src:"src/aplication.js"dest: "dist/aplication.min.js"}}); -
LoadNpmTasks
This property is used to load the plugin:
1grunt.loadNpmTasks('grunt-contrib-uglify'); -
RegisterTask
This property defines alias commands that combine multiple tasks in a specified order.
Example
This propertywill be better explained with the following example:
1task.registerTask('dist', ['concat:dist', 'uglify:dist']);The command alias “dist” from the previous example will perform two operations (concat and uglify) and will run in CMD with only one command:
grunt dist
If we put default as the first parameter of the function, then the default command for the alias “grunt” will be used.
1grunt.registerTask('default', ['build','watch']);The default alias is started with the command:
grunt
See more about this here
NOTE:
When using the grunt.registerTask command, the “watch” task must always be the last item because this task continues until the user interrupts it, which means that the task after it would never start!
Example
The following example shows a possible final appearance of gruntFile.js:
|
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 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
module.exports = function(grunt) { // Defining plugin properties: //--------------------------------------------------------------------------------------------- grunt.initConfig({ //********* .SCSS to .CSS *************** compass: { compile: { options: { sassDir: "assets/scss", // another option is possible: specify: "sass/bootstrap.scss", cssDir: "assets/stylesheets", outputStyle: "nested" // another option is possible: outputStyle: "compressed" }//options }//dev }, //compass //********* PostCSS tj. AUTOPREFIXER *************** postcss: { options: { map: true, // inline sourcemaps processors: [ require('pixrem')(), // add fallbacks for rem units require('autoprefixer')({browsers: 'last 2 versions'}) , // add vendor prefixes require('cssnano')() // minify the result ] }, dist: { src: 'css/*.css' } }, //********* watch *************** watch: { grunt: { files: ['Gruntfile.js'] }, sass: { files: 'scss/**/*.scss', tasks: ['sass'], }, postcss: { files: 'css/*.css', tasks: ['postcss'] } } }); // Loading the plugin: //--------------------------------------------------------------------------------------------- grunt.loadNpmTasks('grunt-postcss'); grunt.loadNpmTasks('grunt-contrib-compass'); grunt.loadNpmTasks('grunt-contrib-watch'); //Alias naredbe //--------------------------------------------------------------------------------------------- grunt.registerTask('default', ['watch']); grunt.registerTask('full', ['compass', 'postcss', 'string-replace']); }; |
Creating a Grunt project using a template
The Grunt project template is used for rapid programming because it allows the use of ready-made templates. You can create templates yourself or use some from github. Read about using the template on the official page here.
Installation of ready-made templates
Before using the prepared templates, we must first install each template that we will use on our computer. In order to install a template, we must first have a globally installed carrying system for the template (grunt-init), if we don’t have it installed, then install it with the command:
npm install -g grunt-init
After this, the command grunt-init is available to us and we can install the template with it.
Template plugins are placed in the .grunt-init folder during installation, so when installing, the path in the command line should be set to:
C:UsersUserName.grunt-init
In the folder .grunt-init we can check if some templates are already installed, although we can do the same with the command:
grunt-init –help
Each template is installed according to the instructions on its official page, although it is most often offered to clone the project.
Windows users need to pay attention to the clone link as they need to make a small change by deleting ~/
from the clone link
Example
This example uses the clone command from the template grunt-init-jquery
C:UsersUsername.grunt-init>git clone https://github.com/gruntjs/grunt-init-jquery.git ~/.grunt-init/jquery
And in order for it to be used on Windows, we have to modify it by deleting “~/”
C:UsersUsername.grunt-init>git clone https://github.com/gruntjs/grunt-init-jquery.git .grunt-init/jquery
Some of the frequently used templates are:
- grunt-init-gruntfile – Creates a basic Gruntfile for JS.
- grunt-init-commonjs – Creates common JS modules including the nodeTEST unit.
- grunt-init-gruntplugin – Creates a Grunt plugin, including the nodeTEST unit.
- grunt-init-jquery – Creates a jQuery plugin, including the nodeTEST unit.
- grunt-init-node – Creates Node.js modules,including the nodeTEST unit.
Creating a Grunt project
Let’s create a folder where we will put our new grunt project, then in the command line, while inside the project folder, create a grunt project according to the template that we have already installed globally, using the command:
|
1 |
grunt-init desiredTemplate |
then it is necessary to download (install) all dependeces listed in package.json with the command:
npm install
Dependeces will be placed in the folder node_modules.
There is an option to make our own custom templates but that is advance topic, more about custom template here.
