Introduction to Grunt
Grunt is a JavaScript task runner, a tool used to automate frequent tasks in the development process, such as minification, compilation, unit testing, linting, and many more. It utilizes a command line interface for running predefined tasks.
Installing Grunt
npm install -g grunt-cli
Basic Usage
To start using Grunt in your project, follow these steps:
- Create a package.json file:
npm init
- Install Grunt in your project:
npm install grunt --save-dev
- Create a Gruntfile.js for configuration.
Grunt Configuration
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), concat: { options: { separator: ';' }, dist: { src: ['src/**/*.js'], dest: 'dist/built.js' } }, uglify: { dist: { files: { 'dist/built.min.js': ['<%= concat.dist.dest %>'] } } }, jshint: { files: ['Gruntfile.js', 'src/**/*.js'], options: { esversion: 6 } }, watch: { files: ['<%= jshint.files %>'], tasks: ['jshint', 'concat', 'uglify'] } }); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.registerTask('default', ['jshint', 'concat', 'uglify']); };
Useful Grunt APIs
grunt.initConfig
Initializes the configuration object for your project:
grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), concat: { options: { separator: ';' }, dist: { src: ['src/**/*.js'], dest: 'dist/built.js' } } });
grunt.loadNpmTasks
Loads npm tasks:
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.registerTask
Registers custom tasks:
grunt.registerTask('default', ['jshint', 'concat', 'uglify']);
Application Example
Suppose you have a simple app where you want to concatenate, minify, and lint JavaScript files:
// Gruntfile.js module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), concat: { options: { separator: ';' }, dist: { src: ['src/**/*.js'], dest: 'dist/app.js' } }, uglify: { dist: { files: { 'dist/app.min.js': ['<%= concat.dist.dest %>'] } } }, jshint: { files: ['Gruntfile.js', 'src/**/*.js'], options: { esversion: 6 } }, watch: { files: ['<%= jshint.files %>'], tasks: ['jshint', 'concat', 'uglify'] } }); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.registerTask('default', ['jshint', 'concat', 'uglify']); };
This configuration will concatenate all JavaScript files in the src
folder, minify them, and then lint them using JSHint.
Hash: e11886944efdd42aefe9ee792b0bd5b025f3059f98ce1423877f8a17ab23868c