What is Grunt?
- A JavaScript task runner
- Automates tasks to make your life easier
What can you use it for?
- Minify files
- Concatenate files
- Compile Sass
- Setup a proxy for you redirecting XHR requests
- Linting
- Unit testing
How to start?
Requirements
- NodeJS
- NPM
Install Grunt
- To make Grunt available on your machine you need to run the following command first
- Install grunt locally in your project
npm install -g grunt-cli
npm install grunt --save-dev
Package.json
- Used to track npm modules
- Manages dependencies
- Placed in the root of your project
npm init
{
"name": "my-project-name",
"version": "0.1.0",
"devDependencies": {
"grunt": "~0.4.5",
"grunt-contrib-jshint": "~0.10.0",
"grunt-contrib-nodeunit": "~0.4.1",
"grunt-contrib-uglify": "~0.5.0"
}
}
Install dependencies
- Fetches all packages and stores them in a new node_modules directory in your project route
npm install
Extra dependencies
- If needed it's possible to add install extra dependencies
- The flag adds the dependency to your package.json
npm install <module> --save-dev
Gruntfile.js
- Define and configure tasks that you want to run
- Add this file if you don't have it yet
Set up Gruntfile
Wrapper
- Set up a "wrapper" function
module.exports = function(grunt) {
// Add configuration, tasks and plugins here
};
initConfig
- Set up the configuration
grunt.initConfig({
// imports the config data from the package.json
pkg: grunt.file.readJSON('package.json'),
task: {
// Add task here
},
task: {
// Add another task here
}
});
Tasks & plugins
What is the difference?
- A task is a configuration within the object passed to grunt.configInit
- A plugin is a convention for creating reusable tasks and publishing them to npm
Load plugins
These need to be specified in your package.json file and installed using npm install. You will get an error when trying to run without installing a plugin.
// Load the Grunt plugins.
grunt.loadNpmTasks('grunt-contrib-compass');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-jshint');
Default tasks
Used to specify a default set of tasks that should run when the grunt command is executed.
// Register the default tasks.
grunt.registerTask('default', ['watch']);
Example
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']);
};
Grunt
By Kim Massaro
Grunt
Basic understanding of Grunt
- 878