grunt作为一个任务管理工具,提供丰富的插件和强大的自动化管理功能。需要安装node及npm。
主要使用到两个文件,一个是npm的依赖配置文件package.json
{
"name": "testGrunt",
"version": "0.1.0",
"description" : "ciaos test",
"author": {
"name" : "ciaos",
"url" : "http://weibo.com/littley"
},
"dependencies": {
"grunt": "0.4.x",
"grunt-autoprefixer": "0.2.x",
"grunt-contrib-clean": "0.5.x",
"grunt-contrib-copy": "0.4.x",
"grunt-contrib-cssmin": "0.6.x",
"grunt-contrib-jshint": "0.6.x",
"grunt-text-replace": "~0.3.9",
"grunt-contrib-uglify": "0.2.x",
"grunt-contrib-watch": "0.5.x"
}
}
另外一个是Gruntfile.js
"use strict"; module.exports = function(grunt) { var Cfg = {
scripts : ["src/scripts/a.js","src/scripts/b.js"],
stylesheets: ["src/stylesheets/*.css"]
},
packageJson = grunt.file.readJSON('package.json'),
banner = '/*! * version: ' + packageJson.name + '\n * build: <%= new Date() %>\n */\n\n'; // Project configuration.
grunt.initConfig({
pkg: packageJson,
uglify: {
options: {
banner: banner
},
build: {
src: Cfg.scripts,
dest: 'build/application.min.js'
}
},
cssmin: {
options: {
banner: banner
},
build: {
src: Cfg.stylesheets,
dest: 'build/application.min.css'
}
},
clean: {
build: {
src: ['build/**']
}
},
watch: {
stylesheets: {
files: Cfg.stylesheets,
tasks: ['buildcss']
},
scripts: {
files: Cfg.scripts,
tasks: ['buildjs']
}
}
}); grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-watch'); // Default task(s).
grunt.registerTask('default', ['uglify', 'cssmin', 'clean']);
grunt.registerTask('buildjs', ['uglify']);
grunt.registerTask('buildcss', ['cssmin']);
grunt.registerTask('buildall', ['uglify', 'cssmin']);
grunt.registerTask('daemon', ['watch']); };
执行grunt 和 grunt daemon(监控文件变化,实时执行任务) ...
在Gruntfile的各个任务还能添加自定义的js函数实现更多的功能。Grunt也提供丰富的api实现比如任务依赖,日志,任务终止,状态查询等功能。