1. what is Grunt
The JavaScript Task Runner .
2.Getting started
Grunt and gruntplugins are installed and managed via npm ,the Node.js package manager.
2.1 Installing the CLI
if you have installed Grunt globally in the past ,you will need to remove it first:
npm uninstall -g grunt
我的机器上之前未安装过Grunt,运行结果为:
In order to get started ,you will want to install grunt's conmand line interface(CLI) globally.You may need to use sudo(for OSX,*nix,BSD etc) or run your command shell as Administrator(for Windows) to do this.
npm install -g grunt-cli
This will put the grunt command in your system path ,allowing it to be run from any directory.
Note that installing grunt-cli does not install the grunt tesk runner ! The job of the grunt CLI is simple :run the version of grunt which has been installed next to a Gruntfile .This allows multiple versions of grunt to be installed on the same machine simultaneously
运行结果:
安装后运行:
grunt --version
grunt-cli v0.1.7 |
2.2 How the CLI works
Each time grunt is run,it looks for a locally installed grunt using node's require() system.Beacause of this,you can run grunt from any subfolder in your project.
If a locally installed Grunt is found ,the CLI loads the local installation of the grunt library,applies the configuration from your Gruntfile ,and executes any tasks you have requested for it to run.
To really understand what is happening,read the code .It is vary short.
(the file is C:\Users\king\AppData\Roaming\npm\node_modules\grunt-cli\bin)
#!/usr/bin/env node
'use strict';
// Especially badass external libs.
var findup = require('findup-sync');
var resolve = require('resolve').sync;
// Internal libs.
var options = require('../lib/cli').options;
var completion = require('../lib/completion');
var info = require('../lib/info');
// Do stuff based on CLI options.
if ('completion' in options) {
completion.print(options.completion);
} else if (options.version) {
info.version();
}
var gruntpath;
try {
gruntpath = resolve('grunt', {basedir: process.cwd()});
} catch (ex) {
gruntpath = findup('lib/grunt.js');
// No grunt install found!
if (!gruntpath) {
if (options.version) { process.exit(); }
if (options.help) { info.help(); }
info.fatal('Unable to find local grunt.', 99);
}
}
// Everything looks good. Require local grunt and run it.
require(gruntpath).cli();
2.3 Working with an existing grunt project
2.4 Preparing a new grunt project
A typical setup will involve adding two files to your project :package.json and the Gruntfile.
package.json:This file is used by npm to store metadata for projects published as npm modules.You will list grunt and the Gruntplugins your project need as devDependencies in the file .
Gruntfile:This file is named Gruntfile.js or Gruntfile.coffee and is used to configure or define task and load Grunt plugins.
This file was named grunt.js for 0.3.x versions of Grunt.
2.4.1 package.json
The package.json file belongs in the root directory of your project,next to the Gruntfile ,and should be commited with your project source.Running npm install in the same folder as a package.json file will install the correct version of each dependency listed themein.
There are a few ways to create a package.json file in your project.
- Most grunt-init templates will automatically create a project-specific package.json file
- The npm init command will create a basic package.json file
- Start with the example below ,and expand as needed ,following the specification.
{
"name": "my-project-name",
"version": "0.1.0",
"devDependencies": {
"grunt": "~0.4.1",
"grunt-contrib-jshint": "~0.1.1",
"grunt-contrib-nodeunit": "~0.1.2"
}
}
Installing Grunt and gruntplugins
The easiest way to add Grunt and gruntplugins to an existing package.json is with the command npm install <module> --save-dev.Not only will this install <module> locally,but it will automatically be added to the devDependencies sections,using a tilde version range.
For example,this will install the latest version of Grunt in your project folder,adding it to your devDependencies:
npm install grunt --save-dev
This same can be done for gruntplugins and other node modules.Be sure to commit the updated package.json file with your project when you are done!
2.4.2 The Gruntfile
The Gruntfile.js or Gruntfile.coffee file is a valid Javascript or CoffeeScript file that belongs in the root directory of your project,next to the package.json file,and should be commited with your project source ,this file was named grunt.js for 0.3.x versions of Grunt.
A Gruntfile is comprised of the following parts:
- The "wrapper" function
- Poject and task configuration
- Loading grunt plugins and tasks
- Custom tasks
An example Gruntfile
In the following Gruntfile,project metadata is imported into the grunt config from the project's package.json file le and the grunt-contrib-uglify plugin's uglify task is configured to minify a source file and generate a banner comment dynamically using that m etadata.when grunt is run on the command line ,the uglify task will be run bydefault.
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']);
};
Now that you have seen the whole Gruntfile ,let's look at its component parts:
- The "wrapper" function
Every Gruntfile (and gruntplugin) uses this basic format,and of your Grunt code must be specified inside this function:
module.exports = function(grunt) {
// Do grunt-related things in here
};
- Project and task configuration
Most Grunt tasks rely on configuration data defined in an object passed to the grunt.initConfig method.
In this example,grunt.file.readJSON('package.json')imports the JSON metadata stored inpackage.jsoninto the grunt config. Because<% %>template strings may reference any config properties, configuration data like filepaths and file lists may be specified this way to reduce repetition.
You may store any arbitrary data inside of the configuration object, and as long as it doesn't conflict with properties your tasks require, it will be otherwise ignored. Also, because this is JavaScript, you're not limited to JSON; you may use any valid JS here. You can even programmatically generate the configuration if necessary.
Like most tasks, the grunt-contrib-uglify plugin'suglifytask expects its configuration to be specified in a property of the same name. Here, thebanneroption is specified, along with a single uglify target namedbuildthat minifies a single source file to a single destination file.
// 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' }
}
});
Loading grunt plugins and tasks
Many commonly used tasks like concatenation, minification and linting are available as grunt plugins. As long as a plugin is specified inpackage.jsonas a dependency, and has been installed vianpm install, it may be enabled inside yourGruntfilewith a simple command:
// Load the plugin that provides the "uglify" task. grunt.loadNpmTasks('grunt-contrib-uglify');
Note: thegrunt --helpcommand will list all available tasks.
Custom tasks
You can configure Grunt to run one or more tasks by default by defining adefaulttask. In the following example, runninggruntat the command line without specifying a task will run theuglifytask. This is functionally the same as explicitly runninggrunt uglifyor evengrunt default. Any number of tasks (with or without arguments) may be specified in the array.
// Default task(s). grunt.registerTask('default', ['uglify']);
If your project requires tasks not provided by a Grunt plugin, you may define custom tasks right inside theGruntfile. For example, this Gruntfile defines a completely customdefaulttask that doesn't even utilize task configuration:
module.exports = function(grunt) { // A very basic default task. grunt.registerTask('default', 'Log some stuff.', function() {
grunt.log.write('Logging some stuff...').ok();
});
};
Custom project-specific tasks don't need to be defined in the Gruntfile; they may be defined in external.jsfiles and loaded via the gruntgrunt.loadTasks method.