這個方案主要是爲了實現js/css/image的壓縮合並、自動添加版本號、自動加瀏覽器前綴和壓縮html。css
先把下面這裏插件 npm i (插件名) -D 安裝到項目環境內html
目錄結構node
|- root
| |-dist //此目錄爲下面生成的
| |-css
| |-js
| |-images
| |-rev
| |-index.html
| |-node_modules
| |-src //資源目錄
| |-css
| |-js
| |-images
| index.html
| gulpfile.js
| package.jsonnpm
gulpfile.js文件json
var gulp = require('gulp'), gulpSequence = require('gulp-sequence'), //同步執行任務 csso = require('gulp-csso'), //css壓縮 jshint = require('gulp-jshint'), //js檢查 uglify = require('gulp-uglify'), //js壓縮 imageMin = require('gulp-imagemin'), //壓縮圖片 htmlMin = require('gulp-htmlmin'), //壓縮html clean = require('gulp-clean'), //清空文件夾 rev = require('gulp-rev'), //更改版本名 md5後綴 autoFx = require('gulp-autoprefixer'), //加瀏覽器前綴 revCollector = require('gulp-rev-collector'); //gulp-rev 的插件,用於html模板更改引用路徑 //清空文件夾 gulp.task('clean', function(){ return gulp.src('dist', {read:false}) .pipe(clean()); }); //壓縮css/加瀏覽器前綴 gulp.task('css', function(){ return gulp.src('src/css/*.css') .pipe(autoFx({ browsers: ['last 2 versions', 'Android >= 4.0'] })) .pipe(csso()) .pipe(rev()) .pipe(gulp.dest('dist/css')) .pipe(rev.manifest()) .pipe(gulp.dest('dist/rev/css')); }); //壓縮js gulp.task('js', function(){ return gulp.src('src/js/*.js') .pipe(uglify()) .pipe(rev()) .pipe(gulp.dest('dist/js')) .pipe(rev.manifest()) .pipe(gulp.dest('dist/rev/js')); }); //壓縮image gulp.task('image', function(){ return gulp.src('src/images/*.{png,jpg,gif,ico}') .pipe(imageMin({ optimizationLevel: 5, progressive: true, interlaced: true, multipass: true })) .pipe(rev()) .pipe(gulp.dest('dist/images')) .pipe(rev.manifest()) .pipe(gulp.dest('dist/rev/images')); }); //改變css引用路徑 gulp.task('revCss',function(){ return gulp.src(['dist/rev/**/*.json','dist/css/*.css']) .pipe(revCollector({ replaceReved: true })) .pipe(gulp.dest('dist/css')); }); //改變html引用路徑 gulp.task('rev', function(){ return gulp.src(['dist/rev/**/*.json','src/*.html']) .pipe(revCollector({ replaceReved: true })) .pipe(htmlMin({collapseWhitespace: true})) .pipe(gulp.dest('dist/')); }); gulp.task('default', gulpSequence('clean', 'css', 'js', 'image', 'revCss', 'rev')); //按順序執行任務
ok! 有問題,不懂的,錯誤,請你們積極留言!gulp