gruntjs是一個基於nodejs的自動化工具,隻要熟悉nodejs或者又一定js經驗就可以熟練應用。
1. 安裝
a. 保證已安裝瞭nodejs,並帶有npm
b.安裝客戶端命令行工具,grunt 主頁都有詳細步驟,註意的是安裝命令行工具而不是服務器版本。
1
npm install –g grunt-cli
安裝完成後已經有瞭grunt,壓縮css,js合並文件換需要grunt的插件,grunt隻是一個平臺,完成各種任務又對應的插件。Grunt的插件十分豐富目前又380個已幫助我們完成工作中的各種任務。
c. grunt插件中名字中有contrib的為官方插件,其他的為第三方插件。
2.進入工程目錄
安裝插件有兩種方式
a.在工程目錄中創建一個package.json文件
列出依賴的插件與對應版本即可
在命令行中進入該目錄,執行
npm install
b.使用命令行工具
npm install grunt-contrib-watch –save-dev
3.創建gruntjs工程文件
a.gruntjs支持兩種語言創建工程文件,可以使用gruntfile.js或者gruntfile.coffee
b.grunt工程文件遵守nodejs模塊,主體結構為
module.exports = function(grunt) {
//ant project
grunt.initConfig({
//task
clean: {
//target
a: ['<%=temp%>']
},
b: ['<%=temp%>']
},
})<br>)}
c. 獲取工程中要使用的插件
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-copy');<br>grunt.loadNpmTasks('grunt-includes');
d.註冊任務
grunt.registerTask('build', ['clean', 'uglify', 'cssmin', 'includes', 'copy', 'clean']);
grunt.registerTask('default', ['build']);
在命令行中執行grunt 就會使用默認任務
要使用某個任務隻用grunt taskname 如
grunt watch
一個完整的gruntjs工程文件(來自項目)
module.exports = function(grunt) {
var rt ='src-dev/',
indexDir = rt + 'index/',
tempDir = rt + 'temp/';
console.log(grunt.option('keys'));
grunt.file.exists(tempDir) && grunt.file.delete(tempDir);
grunt.file.mkdir(tempDir);
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
rt : rt,
temp: tempDir,
index : indexDir,
clean: {
build: ['<%=temp%>']
},
jsdoc : {
dist : {
src : '<%=index%>doc.js',
options : {
destination : '<%=rt%>../out/'
}
}
},
cssmin: {
//debug : true,
combine: {
files: {
'<%=temp%>c.min.css': ['<%=rt%>common/reset.css', '<%=index%>c.css']
}
}
},
includes : {
files: {
//debug: true,
src: ['<%=rt%>**/*.html'],
dest: '<%=temp%>',
cwd: '.',
flatten: true,
options: {
banner: ''
}
}
},
watch : {
files : ['<%=index%>j.js','<%=index%>*.html' ,'<%=index%>c.css'],
tasks : ['clean', 'uglify', 'cssmin', 'includes', 'copy', 'clean'],
//debug : true,
options: {
livereload: true
}
},
uglify: {
dist: {
files: {
'<%=temp%>j.js': ['<%=index%>*.js']
}
}
},
copy: {
main: {
files: [
{
flatten: true,
expand: true,
filter: 'isFile',
src: ['<%=temp%>index.html'],
dest: '<%=rt%>../src/'
},
//{src: ['<%=temp%>doc/**'], dest: '<%=temp%>../'},
]
}
}
});
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-includes');
grunt.loadNpmTasks('grunt-devtools');
grunt.registerTask('build', ['clean', 'uglify', 'cssmin', 'includes', 'copy', 'clean']);
grunt.registerTask('default', ['build']);
};