gulp配置前端资源自动化 -- 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');
// 同步运行任务插件
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');
// 清空数据
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'));
});
// 图片压缩任务
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图任务
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'))
});
// 默认执行任务
gulp.task('default', function(callback) {
runSequence([
'clean:dist',
'buildCss',
'buildJs',
'buildImages',
'sprite'
], callback);
})
3.安装模块
npm install
4.运行
glup