安裝node.js npm 以及安裝gulp等方法我就不在這裏贅述了。css
接下里我主要介紹的是Gulpfile文件裏面的配置該如何書寫。html
var gulp = require('gulp');//引入gulp組件
// 引入組件
//在引入這些組件前你須要在你的項目裏進行安裝。舉個栗子:組件中間用空格隔開。必定要先切換到你項目所在的目錄
//npm install gulp-jshint gulp-sass gulp-concat gulp-uglify gulp-rename --save-devnode
var htmlmin = require('gulp-htmlmin'), //html壓縮 imagemin = require('gulp-imagemin'),//圖片壓縮 pngcrush = require('imagemin-pngcrush'), minifycss = require('gulp-minify-css'),//css壓縮 jshint = require('gulp-jshint'),//js檢測 uglify = require('gulp-uglify'),//js壓縮 concat = require('gulp-concat'),//文件合併 rename = require('gulp-rename'),//文件改名 notify = require('gulp-notify');//提示信息// 壓縮htmlgulp.task('html', function() { return gulp.src('src/*.html') .pipe(htmlmin({collapseWhitespace: true})) .pipe(gulp.dest('./dest')) .pipe(notify({ message: 'html task ok' }));});// 壓縮圖片gulp.task('img', function() { return gulp.src('src/images/*') .pipe(imagemin({ progressive: true, svgoPlugins: [{removeViewBox: false}], use: [pngcrush()] })) .pipe(gulp.dest('./dest/images/')) .pipe(notify({ message: 'img task ok' }));});// 合併、壓縮、重命名cssgulp.task('css', function() { return gulp.src('src/css/*.css') .pipe(concat('main.css')) .pipe(gulp.dest('dest/css')) .pipe(rename({ suffix: '.min' })) .pipe(minifycss()) .pipe(gulp.dest('dest/css')) .pipe(notify({ message: 'css task ok' }));});// 檢查jsgulp.task('lint', function() { return gulp.src('src/js/*.js') .pipe(jshint()) .pipe(jshint.reporter('default')) .pipe(notify({ message: 'lint task ok' }));});// 合併、壓縮js文件gulp.task('js', function() { return gulp.src('src/js/*.js') .pipe(concat('all.js')) .pipe(gulp.dest('dest/js')) .pipe(rename({ suffix: '.min' })) .pipe(uglify()) .pipe(gulp.dest('dest/js')) .pipe(notify({ message: 'js task ok' }));});// 默認任務gulp.task('default', function(){ gulp.run('img', 'css', 'lint', 'js', 'html'); // 監聽html文件變化 gulp.watch('src/*.html', function(){ gulp.run('html'); }); // Watch .css files gulp.watch('src/css/*.css', ['css']); // Watch .js files gulp.watch('src/js/*.js', ['lint', 'js']); // Watch image files gulp.watch('src/images/*', ['img']);});