gulp js压缩

安装nodejs、gulp

  • 安装 nodejs
1
brew install node
  • 安装 gulp
1
npm install -g gulp

安装gulp插件

1
npm install gulp-htmlmin gulp-imagemin imagemin-pngcrush gulp-minify-css gulp-jshint gulp-uglify gulp-concat gulp-rename gulp-notify --save-dev

gulp配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
//在你的项目根目录下创建gulpfile.js,代码如下:
// 引入 gulp
var gulp = require('gulp');
// 引入组件
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');//提示信息
// 压缩html
gulp.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' }));
});
// 合并、压缩、重命名css
gulp.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' }));
});
// 检查js
gulp.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']);
});

热评文章