寫在前面:css
本配置支持es六、less、reacthtml
1.首先react
給出初始的目錄結構es6
給出執行gulp後的目錄結構npm
給出執行gulp --p後的目錄結構json
2.package.json裏是一個寫入。文件描述了npm包的相關配置信息(做者、簡介、包依賴等)和所需模塊。gulp
{ "name": "gruntTest", "version": "1.0.0", "description": "", "main": "Gulpfile.js" }
3.Gulpfile.js添加要執行的任務babel
var gulp = require('gulp'); var uglify = require('gulp-uglify'); //js壓縮 var concat = require('gulp-concat'); //合併文件 var minifyCSS = require('gulp-minify-css'); //css壓縮 var less = require('gulp-less'); //less var changedInPlace = require('gulp-changed-in-place');//無論修改哪一個文件,gulp會簡化DEST裏的html文件 var minifyHTML = require('gulp-htmlmin'); //簡化html var browserSync = require('browser-sync').create(); //自動刷新 var babel = require('gulp-babel'); //支持es6 var argv = require('yargs').argv; //支持不一樣環境 var sequence = require('gulp-sequence'); //按照順序執行 var watch = require('watch'); //監聽 var clean = require('gulp-clean'); //監聽 //npm install --save-dev gulp-babel babel-preset-es2015 var DEST = 'dest/'; var HTML_PATH = './src/*.html'; gulp.task('minify-js', function(){ if(argv.p){ gulp.src('src/source/*.js') .pipe(babel({ presets: ['es2015','react'] })) .pipe(uglify()) .pipe(concat('gruntTest.min.js')) .pipe(gulp.dest(DEST+'js')) }else{ gulp.src('src/source/*.js') .pipe(babel({ presets: ['es2015','react'] })) .pipe(uglify()) .pipe(concat('gruntTest.min.js')) .pipe(gulp.dest('src/js')) } }); gulp.task('minify-css', function(){ if(argv.p){ gulp.src('src/less/*.less') //或者用['src/less/p1.less','src/less/p2.less'] .pipe(less()) .pipe(minifyCSS()) .pipe(concat('style.min.css')) .pipe(gulp.dest(DEST+'css')) .pipe(browserSync.stream()); }else{ gulp.src('src/less/*.less') //或者用['src/less/p1.less','src/less/p2.less'] .pipe(less()) .pipe(minifyCSS()) .pipe(concat('style.min.css')) .pipe(gulp.dest('src/css')) .pipe(browserSync.stream()); } }); gulp.task('minify-html', function(){ gulp.src(HTML_PATH) .pipe(changedInPlace({firstPass: true})) .pipe(minifyHTML({collapseWhitespace: true})) .pipe(gulp.dest(DEST)) .pipe(browserSync.stream()); }); gulp.task('clean', function () { gulp.src(['./src/css/*.css','./src/js/*.js'], {read: false}) .pipe(clean()); }); var files = [ './src/css/*.css', './src/js/*.js' ]; gulp.task('browser-sync', function(){ browserSync.init(files,{ server: { baseDir: './' }, port: 9999 }); }); gulp.task('watch', function() { gulp.watch('./src/source/*.js',['minify-js']); gulp.watch('./src/less/*.less',['minify-css']); }); if(argv.p){ //product gulp.task('default', sequence('minify-js','minify-css','minify-html','browser-sync')); }else{ //develop gulp.task('default', sequence('clean','minify-js','minify-css','watch','browser-sync')); }
4.擴展less
(1)上面一堆require看着好煩人,也很龐大。此處能夠引入「gulp-load-plugins」插件grunt
var gulpLoadPlugins = require('gulp-load-plugins'), plugins = gulpLoadPlugins(); plugins.uglify();便可執行相應任務
(2)若某個文件夾下好多文件,那麼watch監聽時須要一一列舉,能夠目錄寫成json格式(例如src.source.*.js)。經過引入「fs」插件,用fs.freaddirSync()方法去讀路徑。循環便可,此處的實現純屬寫js代碼。