一 安裝gulp和bower
gulp安裝: npm install -g gulp
bower安裝: npm install -g bower
==注:== angularjs的一些包文件我們是通過bower來管理的
二 bower使用
- 使用bower初始化一個項目: bower init
- 填寫工程名,描述等等那些東西
- 安裝angularjs:bower install --save angular
- 創建.bowerrc文件(注意window最好用命令行創建)
三 自動化工具gulp的使用
- 初始化文件:npm init(一直回車下去就可以)
- 在項目裏面安裝gulp:npm i --save-dev gulp
- 安裝gulp的依賴插件(只介紹項目中用到的)gulp-clean,gulp-concat,gulp-connect,gulp-cssmin,gulp-imagemin,gulp-less,gulp-load-plugins,gulp-uglify,open(可以和上面安裝gulp一樣安裝)
- 創建gulpfile.js來編寫gulp的配置
// 依賴
var gulp = require('gulp');
// 進行實例化(gulp-load-plugins這個模塊後面可以通過$來操作)
var $ = require('gulp-load-plugins')();
// open模塊
var open = require('open');
var app = {
srcPath: 'src/', //源代碼路徑
devPath: 'build/', //整合後的路徑,開發路徑
prdPath: 'dist/' //生產環境路徑
};
// 創建任務
gulp.task('lib', function () {
gulp.src('bower_components/**/*.js')
.pipe(gulp.dest(app.devPath + 'vendor'))
.pipe(gulp.dest(app.prdPath + 'vendor'))
.pipe($.connect.reload());
});
/*
* html任務
* 創建目錄src,在src下創建index.html
* 創建視圖模版目錄view,在其中存放視圖view的模版
*/
gulp.task('html', function () {
gulp.src(app.srcPath + '**/*.html')
.pipe(gulp.dest(app.devPath))
.pipe(gulp.dest(app.prdPath))
.pipe($.connect.reload());
});
/*
* json任務
*/
gulp.task('json', function () {
gulp.src(app.srcPath + 'data/**/*.json')
.pipe(gulp.dest(app.devPath + 'data'))
.pipe(gulp.dest(app.prdPath + 'data'))
.pipe($.connect.reload());
});
/*
* css任務
* 在src下創建style文件夾,裏面存放less文件。
*/
gulp.task('less',function () {
gulp.src(app.srcPath + 'style/index.less')
.pipe($.less())
.pipe(gulp.dest(app.devPath + 'css'))
.pipe($.cssmin())
.pipe(gulp.dest(app.prdPath + 'css'))
.pipe($.connect.reload());
});
/*
* js任務
* 在src目錄下創建script文件夾,裏面存放所有的js文件
*/
gulp.task('js', function () {
gulp.src(app.srcPath + 'script/**/*.js')
.pipe($.concat('index.js'))
.pipe(gulp.dest(app.devPath + 'js'))
.pipe($.uglify())
.pipe(gulp.dest(app.prdPath + 'js'))
.pipe($.connect.reload());
});
/*
* image任務
*
*/
gulp.task('image', function () {
gulp.src(app.srcPath + 'image/**/*')
.pipe(gulp.dest(app.devPath + 'image'))
.pipe($.imagemin()) // 壓縮圖片
.pipe(gulp.dest(app.prdPath + 'image'))
.pipe($.connect.reload());
});
// 每次發佈的時候,可能需要把之前目錄內的內容清除,避免舊的文件對新的容有所影響。 需要在每次發佈前刪除dist和build目錄
gulp.task('clean', function () {
gulp.src([app.devPath, app.prdPath])
.pipe($.clean());
});
// 總任務
gulp.task('build', ['image', 'js', 'less', 'lib', 'html', 'json']);
// 服務
gulp.task('serve', ['build'], function () {
$.connect.server({ //啓動一個服務器
root: [app.devPath], // 服務器從哪個路徑開始讀取,默認從開發路徑讀取
livereload: true, // 自動刷新
port: 1234
});
// 打開瀏覽器
open('http://localhost:1234');
// 監聽
gulp.watch('bower_components/**/*', ['lib']);
gulp.watch(app.srcPath + '**/*.html', ['html']);
gulp.watch(app.srcPath + 'data/**/*.json', ['json']);
gulp.watch(app.srcPath + 'style/**/*.less', ['less']);
gulp.watch(app.srcPath + 'script/**/*.js', ['js']);
gulp.watch(app.srcPath + 'image/**/*', ['image']);
});
// 定義default任務
gulp.task('default', ['serve']);