Grunt is a task runner. Basically what Grunt does is automate some tasks like concatenating multiple files, converting LESS to CSS etc.
In this post I will discuss the very fundamentals of Grunt.
To Start using Grunt we first need to install it.
- install grunt cli globally so that we can use it anywhere and do not need to install it whenever we create a project
npm install grunt-cli -g
- create a package.json file
npm init
- install grunt locally
npm install grunt --save-dev
create a new file named Gruntfile.js. In this file we control the configuration of plugins that we install and where we register the tasks.
We can install different plugins from the list available in Link.
Eg: npm install grunt-contrib-concat --save-dev
'contrib' suggests that it is maintained by the Grunt team.
Gruntfile.js
module.exports = (grunt) => {
// configuration
grunt.initConfig({
// pass in options to plugins, references to files etc
// "concat" -- anything after "grunt-contrib-"
concat: {
js: {
src: ['js/a.js', 'js/b.js']
// src: ['js/*.js']; -- * all js files in folder
, dest: 'build/scripts.js'
},
css: {
src: ['css/*.css'],
dest: 'build/styles.css'
}
},
uglify: {
build: {
files: [{
src: 'build/scripts.js',
dest: 'build/scripts_compressed' // if we write 'build/scripts.js' then it will overwrite
}]
}
},
watch: {
csswatch: {
files: ['css/*.css']
}
},
less: {
build: {
files: [{
src: 'css/less/xy.less',
dest: 'build/xyz.css'
}]
}
},
jshint: {
all: ['js/*.js']
},
htmlmin: {
files: {
src: ['html/*.html'],
dest: 'dist/',
expand: true,
flatten: true,
ext: '.html',
extDot: 'last'
}
}
});
//load plugin
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-htmlmin');
};
- We can run by typing grunt run ... . Eg.
grunt run jshint
The Net Ninja has some good beginner Grunt tutorials in Youtube which you can check out.
I hope following this article you can install Grunt and start with some basic task.
Thanks for reading.
Top comments (0)