版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
打包一个静态网站,如果用 Webpack,实在有些麻烦。使用 Gulp,就好像它对自己的定义那样:
使用 Gulp 需要安装如下依赖:
"devDependencies": {
"gulp": "^4.0.0",
"gulp-cache": "^1.1.1",
"gulp-csso": "^3.0.1",
"gulp-filter": "^5.1.0",
"gulp-imagemin": "^5.0.3",
"gulp-notify": "^3.2.0",
"gulp-rev": "^9.0.0",
"gulp-rev-replace": "^0.4.4",
"gulp-uglify": "^3.0.1",
"gulp-useref": "^3.1.6",
"imagemin-pngcrush": "^6.0.0"
}
随后项目根目录下新建 gulpfile.js 文件:
const gulp = require('gulp');
const rev = require('gulp-rev');
const revReplace = require('gulp-rev-replace');
const useref = require('gulp-useref');
const filter = require('gulp-filter');
const uglify = require('gulp-uglify');
const csso = require('gulp-csso');
const imagemin = require('gulp-imagemin');
const cache = require('gulp-cache');
const notify = require('gulp-notify');
gulp.task('default', function(){
const jsFilter = filter('**/*.js', {restore: true});
const cssFilter = filter('**/*.css', {restore: true});
const indexHtmlFilter = filter(['**/*', '!**/*.html'], {restore: true});
const stream = gulp.src('*.html')
.pipe(useref())
.pipe(jsFilter)
.pipe(uglify())
.pipe(jsFilter.restore)
.pipe(cssFilter)
.pipe(csso())
.pipe(cssFilter.restore)
.pipe(indexHtmlFilter)
.pipe(rev())
.pipe(indexHtmlFilter.restore)
.pipe(revReplace())
.pipe(gulp.dest('dist'));
return stream;
});
//打包图片,新增图片,则需重新执行此任务
gulp.task('images', function() {
return gulp.src('img/**/*')
.pipe(cache(imagemin({
optimizationLevel: 3,
progressive: true,
interlaced: true
})))
.pipe(gulp.dest('dist/img'))
.pipe(notify({
message: 'Images task complete'
}));
});
//用于打包 favicon, 其不改变的情况下,无需执行
gulp.task('favicon', function () {
return gulp.src('favicon.ico')
.pipe(cache(imagemin({
optimizationLevel: 3,
progressive: true,
interlaced: true
})))
.pipe(gulp.dest('dist/'))
.pipe(notify({
message: 'Icon task complete'
}));
});
在 HTML 文件引入的 CSS 和 js 文件的部分添加如下注释,以便 Gulp Task 识别并进行打包任务的执行:
<!-- build:css css/combined.css -->
<link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="css/modern-business.css" rel="stylesheet">
<!-- endbuild -->
<!-- build:js scripts/combined.js -->
<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- endbuild -->
打包后生成的 dist 文件目录结构如下:
.
├── css
│ └── combined-82e2623401.css
├── favicon.ico
├── img
│ ├── list1.jpg
│ ├── list2.jpg
│ ├── list3.jpg
│ ├── logo.png
│ └── main.jpg
├── index.html
└── scripts
└── combined-bf741cdc1d.js
Favicon 的引入,type 要定义为 favicon:
<link rel="icon" type="favicon" href="./favicon.ico">
部署到服务器,将打包后生成的 dist 文件夹复制粘贴到服务器的 Tomcat ROOT 目录下:
apache-tomcat-7.0.59/webapps/ROOT
设置好端口号,'remote server ip: port#' 就可以访问了。