標籤:
1.認識grunt
grunt是什麼:他是一套前端自動化工具,是一個基於nodejs的命令列工具。(Grunt和Grunt外掛程式是通過npm 安裝並管理的,所以首先要安裝nodejs)。
grunt能幹什麼:1.壓縮檔 2.合并檔案 3.簡單的語法檢查 4.監聽檔案變動 5.less編譯
grunt優點:1.減輕勞動,簡化工作 2.免費,沒有盜版 3.外掛程式多,而且可以自己編寫外掛程式
2.grunt安裝與使用
第一步:添加package.json和gruntfile.js檔案
package.json配置項的添加方式:
a:手動添加 (下面內容已經將基本的grunt外掛程式寫好)
{
"name": "grunt_test",
"version": "0.0.1",
"description": "grunt test",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"devDependencies": {
"grunt": "^0.4.5",
"grunt-contrib-jshint": "*",
"grunt-contrib-uglify": "*",
"grunt-contrib-cssmin":"*",
"grunt-contrib-imagemin":"*",
"grunt-contrib-watch": "*",
"grunt-contrib-concat":"*"
},
"keywords": [
"grunt"
],
"author": "caihe",
"license": "ISC"
}
說明:
grunt-contrib-jshint: 檢查javascript文法
grunt-contrib-uglify: 壓縮以及合并js檔案
grunt-contrib-cssmin:壓縮以及合并css檔案
grunt-contrib-imagemin:映像壓縮模組
grunt-contrib-watch:監視檔案變動,做出相應動作
grunt-contrib-concat:合并檔案
然後cmd視窗中進入到當前項目的根目錄輸入命令列 :npm install
b:命令列實現:npm install grunt-contrib-jshint --save-dev等
gruntfile.js檔案配置:
gruntfile.js 的作用1.讀取package.json的資訊 2.外掛程式載入、註冊任務、運行任務
module.exports = function(grunt){
//項目配置
grunt.initConfig({
//讀取配置項
pkg:grunt.file.readJSON("package.json"),
//具體任務
uglify:{
options:{
//加註釋
banner:"/* 這個檔案 <%= pkg.name %><%= pkg.version%> \n*/"
},
build:{
//被壓縮的檔案的路徑
src: "src/jquery-1.9.1.js",
//被壓縮後的檔案路徑
dest:"dest/jquery-1.9.1.min.js"
}
},
//合并
concat:{
options:{
//加註釋
banner:"/* 這個檔案 <%= pkg.name %><%= pkg.version%> 合并的js\n*/"
},
build:{
//被壓縮的檔案的路徑
src: "src/*.js",
//被壓縮後的檔案路徑
dest:"dest/concat.js"
}
},
jshint: {
files: [‘Gruntfile.js‘],
options: {
}
},
watch: {
files: [‘src/*.html‘,‘src/*.css‘],
tasks: [‘jshint‘]
}
});
//載入外掛程式
grunt.loadNpmTasks("grunt-contrib-uglify");
grunt.loadNpmTasks(‘grunt-contrib-jshint‘);
grunt.loadNpmTasks(‘grunt-contrib-watch‘);
grunt.loadNpmTasks(‘grunt-contrib-concat‘);
//預設執行任務
grunt.registerTask("default",["uglify","concat","jshint",‘watch‘]);
};
然後cmd視窗中進入到當前項目的根目錄輸入命令列 :grunt
可執行grunt任務grunt watch可監聽檔案變化
windows下grunt的快速入門