雖然網(wǎng)上有很多的 gulp 構(gòu)建文章,但是很多都已經(jīng)隨著 gulp 插件的更新無法運(yùn)行了。因此,我寫了這個比較簡單的構(gòu)建方案。
如果還不熟悉 gulp 的插件,可以閱讀上一篇文章:精通gulp常用插件
這個方案主要是為了實現(xiàn)js/css的壓縮合并、自動添加版本號和壓縮html。
- gulp-csso 壓縮優(yōu)化css
- gulp-uglify 壓縮js
- gulp-html-minify 壓縮html
- gulp-rev-all 生成版本號
主要通過上面插件實現(xiàn)功能,其他插件配合使用。
// gulpfile.js
var gulp = require('gulp'),
htmlmini = require('gulp-html-minify'),
useref = require('gulp-useref'),
uglify = require('gulp-uglify'),
csso = require('gulp-csso'),
filter = require('gulp-filter'),
RevAll = require('gulp-rev-all'),
del = require('del');
gulp.task('default',['del'], function () {
var jsFilter = filter('**/*.js',{restore:true}),
cssFilter = filter('**/*.css',{restore:true}),
htmlFilter = filter(['**/*.html'],{restore:true});
gulp.src('/*.html')
.pipe(useref()) // 解析html中的構(gòu)建塊
.pipe(jsFilter) // 過濾所有js
.pipe(uglify()) // 壓縮js
.pipe(jsFilter.restore)
.pipe(cssFilter) // 過濾所有css
.pipe(csso()) // 壓縮優(yōu)化css
.pipe(cssFilter.restore)
.pipe(RevAll.revision({ // 生成版本號
dontRenameFile: ['.html'], // 不給 html 文件添加版本號
dontUpdateReference: ['.html'] // 不給文件里鏈接的html加版本號
}))
.pipe(htmlFilter) // 過濾所有html
.pipe(htmlmini()) // 壓縮html
.pipe(htmlFilter.restore)
.pipe(gulp.dest('/dist'))
})
gulp.task('del',function () {
del('/dist'); // 構(gòu)建前先刪除dist文件里的舊版本
})
在html中,我們需要先定義好構(gòu)建塊。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>gulp自動化構(gòu)建解決方案</title>
<!-- build:css static/css/index.css --> // 定義了構(gòu)建后引用的css路徑
<link rel="stylesheet" href="static/css/common.css"/>
<link rel="stylesheet" href="static/css/index.css"/>
<!-- endbuild -->
</head>
<body>
......
<!-- build:js static/js/index.js --> // 定義了構(gòu)建后引用的js路徑
<script src="static/js/jquery.js"></script>
<script src="static/js/common.js"></script>
<script src="static/js/index.js"></script>
<!-- endbuild -->
</body>
</html>
執(zhí)行構(gòu)建完成后,會生成 dist 文件夾,目錄為:
|-dist
| |-static
| |-css
| |-index.96cf44da.css
| |-js
| |-index.42ce3282.js
| |-index.html
構(gòu)建完的index.html,我們忽略壓縮的html,完成了壓縮合并添加版本號等功能。
// dist/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>gulp自動化構(gòu)建解決方案</title>
<link rel="stylesheet" href="static/css/index.96cf44da.css"/>
</head>
<body>
......
<script src="static/js/index.42ce3282.js"></script>
</body>
</html>