前端越來越復(fù)雜。
用Grunt來生成任務(wù)和處理。用npm和bower來管理客戶端的包街望。
準備開發(fā)環(huán)境
node.js
首先在node.js的官方網(wǎng)站下載最新的node.js。
git
在git官網(wǎng)上下載并安裝弟跑。
和mac不同灾前,需要設(shè)置一下環(huán)境變量。
C:\Program Files (x86)\Git\bin
Compass(Mac下)
Compass安裝需要依賴于Ruby Gems孟辑,執(zhí)行下面的步驟:
sudo gem update --system
sudo gem install compass
運行上面的代碼有可能會失敗哎甲,是由于ruby的gem被和諧了,不過淘寶的ruby工程師提供了rubygems的國內(nèi)鏡像饲嗽。
$ gem sources --remove https://rubygems.org/$ gem sources -a https://ruby.taobao.org/$ gem sources -l*** CURRENT SOURCES ***https://ruby.taobao.org
運行上面的代碼再新執(zhí)行炭玫,就成功了。
安裝grunt bower
npm install -g grunt-cli bower
配置
安裝grunt-init
grunt-init用來初始化Grunt項目貌虾。
npm install -g grunt-init
安裝grunt-init-gruntfile模板
grunt-init-gruntfile用來生成最簡單的gruntfile.js和package.json吞加。
git clone https://github.com/gruntjs/grunt-init-gruntfile.git ~/.grunt-init/gruntfile
接著在web項目的根目錄,執(zhí)行下面的代碼
grunt-init gruntfile
執(zhí)行成功后尽狠,就可以看到gruntfile.js和package.json已經(jīng)生成了衔憨。
安裝 npm 包
vs2013上沒有反應(yīng),報錯袄膏。發(fā)現(xiàn)好像是被墻的原因践图。
用下面的代碼把npm的地址換到國內(nèi)淘寶提供的服務(wù)器就好了。
npm config delete http-proxy
npm config delete https-proxy
npm install -g cnpm --registry=http://r.cnpmjs.org
npm install microtime --registry=http://r.cnpmjs.org --disturl=http://dist.cnpmjs.org
bower
首先在項目目錄下執(zhí)行哩陕,初始化bower.json
bower init
安裝我們必要的包
bower install bootstrap --save
bower install jquery --save
grunt教程
grunt是用來執(zhí)行例如壓縮平项、編譯、單元測試悍及、linting等工作的自動化工具闽瓢。
less編譯
首先我們需要用到兩個npm包
"grunt-contrib-less": "*",
"grunt-contrib-watch": "*"
grunt-contrib-less是用來把less編譯成css的,grunt-contrib-watch可以監(jiān)視文件的改變并自動執(zhí)行心赶。
我們接下來編寫我們的gruntfile.js
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
less: {
//compile
compile: {
files: {
'assets/css/bootstrap.css': "bower_components/bootstrap/less/bootstrap.less"
}
},
//compress
yuicompress: {
files: {
'assets/css/bootstrap.min.css': "assets/css/bootstrap.css"
},
options: {
yuicompress:true
}
}
},
watch: {
scripts: {
files: ["bower_components/bootstrap/less/*.less"],
task:["less"]
}
}
});
grunt.loadNpmTasks("grunt-contrib-less");
grunt.loadNpmTasks("grunt-contrib-watch");
grunt.registerTask("default", ['less', 'watch']);
};
執(zhí)行一下扣讼,less編譯成功。
不過這里遇到了一個問題缨叫,css沒有壓縮椭符。
因此在grunt上找到了另外一個插件grunt-contrib-cssmin來做css壓縮工作。
在gruntfile.js中加入一個任務(wù)
cssmin: {
css: {
src: ["assets/css/bootstrap.css"],
dest:"assets/css/bootstrap.min.css"
}
},
尤其注意的是要把cssmin任務(wù)放在watch任務(wù)的前面耻姥。
grunt.registerTask("default", ['less',"cssmin", 'watch']);