前端优化之静态资源优化

前端优化之静态资源优化

废话不多说,使用gulp自动化构建工具来压缩代码文件。

1.安装gulp

1
2
$ npm install gulp -g
$ npm install gulp gulp-htmlclean gulp-htmlmin gulp-minify-css gulp-uglify --save

或者配置package.json后执行$ npm install

1
2
3
4
5
6
7
"dependencies": {
"gulp": "^3.9.1",
"gulp-htmlclean": "^2.7.14",
"gulp-htmlmin": "^3.0.0",
"gulp-minify-css": "^1.2.4",
"gulp-uglify": "^2.1.2",
}

2.创建gulpfile.js

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
/*
* @此配置用于hexo
*/

var gulp = require('gulp');
var minifycss = require('gulp-minify-css');
var uglify = require('gulp-uglify');
var htmlmin = require('gulp-htmlmin');
var htmlclean = require('gulp-htmlclean');

// 压缩 public 目录 css
gulp.task('minify-css', function() {
return gulp.src('/gallery/public/**/*.css')
.pipe(minifycss())
.pipe(gulp.dest('/gallery/public'));
});

// 压缩 public 目录 html
gulp.task('minify-html', function() {
return gulp.src('/gallery/public/**/*.html')
.pipe(htmlclean())
.pipe(htmlmin({
removeComments: true, //清除HTML注释
collapseWhitespace: true, //压缩HTML
collapseBooleanAttributes: true, //省略布尔属性的值 <input checked="true"/> ==> <input checked />
removeEmptyAttributes: true, //删除所有空格作属性值 <input id="" /> ==> <input />
removeScriptTypeAttributes: true, //删除<script>的type="text/javascript"
removeStyleLinkTypeAttributes: true, //删除<style>和<link>的type="text/css"
minifyJS: true, //压缩页面JS
minifyCSS: true //压缩页面CSS
}))
.on('error', function(err) {
console.log('html Error!', err.message);
this.end();
})
.pipe(gulp.dest('/gallery/public'))
});

// 压缩 public/js 目录 js
gulp.task('minify-js', function() {
return gulp.src('/gallery/public/**/*.js')
.pipe(uglify())
.pipe(gulp.dest('/gallery/public'));
});

// 执行 gulp 命令时执行的任务
gulp.task('default', [
'minify-html','minify-css','minify-js',
]);

3.压缩静态资源

以后generate的时候跟上gulp命令即可压缩静态资源。

1
2
3
$ hexo g
$ gulp
$ hexo d

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×