gulp配置前端資源自動(dòng)化 -- less編譯 js壓縮 圖片壓縮
1.package.json 文件
{
"name": "example-static",
"version": "0.0.1",
"description": "example-static",
"author": "c.c.",
"license": "ISC",
"dependencies": {
"gulp": "^3.9.1"
},
"devDependencies": {
"del": "^2.2.2",
"gulp-autoprefixer": "^3.1.1",
"gulp-if": "^2.0.2",
"gulp-imagemin": "^3.1.1",
"gulp-less": "^3.3.0",
"gulp-sourcemaps": "^2.4.1",
"gulp-uglify": "^2.1.2",
"gulp.spritesmith": "^6.4.0",
"imagemin-pngquant": "^5.0.0",
"run-sequence": "^1.2.2"
}
}
2.gulpfile.js 文件
var gulp = require('gulp');
// 編譯less
var less = require('gulp-less');
// 給css3屬性添加瀏覽器前綴插件
var autoprefixer = require('gulp-autoprefixer');
// 刪除文件插件
var del = require('del');
// 同步運(yùn)行任務(wù)插件
var runSequence = require('run-sequence');
// 壓縮js插件
var uglify = require('gulp-uglify');
var gulpIf = require('gulp-if');
var sourcemaps = require('gulp-sourcemaps');
// 壓縮圖片插件
var imagemin = require('gulp-imagemin');
// 壓縮png圖片的插件
var pngquant = require('imagemin-pngquant');
// 合成sprite圖片插件
var spritesmith = require('gulp.spritesmith');
// 清空數(shù)據(jù)
gulp.task('clean:dist', function() {
return del.sync('dist');
});
// 編譯less
gulp.task('buildCss', function() {
gulp.src(['static/seller/less/**/*.less'])
.pipe(less())
.pipe(gulp.dest('dist/seller/css'))
gulp.src(['static/ec/less/**/*.less'])
.pipe(less())
.pipe(gulp.dest('dist/ec/css'))
});
// 壓縮js插件
gulp.task('buildJs', function() {
gulp.src(['static/seller/js/**/*.js'])
.pipe(gulpIf('*.js', uglify()))
.pipe(sourcemaps.write('maps'))
.pipe(gulp.dest('dist/seller/js'));
});
// 圖片壓縮任務(wù)
gulp.task('buildImages', function() {
gulp.src('static/seller/images/**/*.+(png|jpg|gif|svg)')
.pipe(imagemin({
progressive: true,
svgoPlugins: [{ removeViewBox: false }],
use: [pngquant()]
}))
.pipe(gulp.dest('dist/seller/images'));
});
// 合并sprite圖任務(wù)
gulp.task('sprite', function() {
var spriteData = gulp.src('static/seller/images/CCoin/*.png')
.pipe(spritesmith({
imgName: 'images/CCoin/sprite.png',
cssName: 'less/CCoin/sprite.less',
cssFormat: 'less',
padding: 10
}));
return spriteData.pipe(gulp.dest('dist/seller'))
});
// 默認(rèn)執(zhí)行任務(wù)
gulp.task('default', function(callback) {
runSequence([
'clean:dist',
'buildCss',
'buildJs',
'buildImages',
'sprite'
], callback);
})
3.安裝模塊
npm install
4.運(yùn)行
glup