新建gulpfile.js文件
const gulp = require('gulp');
const babel = require('gulp-babel'); // 语法转换
const concat = require('gulp-concat'); // 合并
const uglify = require('gulp-uglify'); // js压缩
const sass = require('gulp-sass'); // scc编译
const htmlmin = require('gulp-htmlmin'); //html压缩
const watch = require('gulp-watch');// 监听文件
const connect = require('gulp-connect'); // 服务
const imagemin = require('gulp-imagemin'); // 图片压缩
const rev = require('gulp-rev');//对文件名加MD5后缀
const revCollector = require('gulp-rev-collector');//替换路径
const del = require('del');// 清空目录
const minifyCSS = require('gulp-minify-css'); //css压缩
// es6语法转换 js压缩 md5命名
gulp.task('js', async() => {
await gulp.src('./app/js/*.js')
.pipe(babel())
.pipe(uglify())
.pipe(rev())
.pipe(gulp.dest('./dist/js'))
.pipe(rev.manifest('rev-js-manifest.json'))
.pipe(gulp.dest('./dist/rev'))
.pipe(connect.reload())
});
// scss编译成css
gulp.task("scss", async () => {
await gulp.src('./app/scss/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./app/css'))
});
// scc合并压缩
gulp.task("css", async() => {
await gulp.src(['./app/css/index.css', './app/css/base.css'])
.pipe(concat('index.css'))
.pipe(minifyCSS({keepBreaks:true}))
.pipe(rev())
.pipe(gulp.dest('./dist/css'))
.pipe(rev.manifest('rev-css-manifest.json'))
// .pipe(rev.manifest())
.pipe(gulp.dest('./dist/rev'))
.pipe(connect.reload())
})
// 压缩图片
gulp.task('img', async () => {
await gulp.src('./app/img/*')
.pipe(imagemin())
.pipe(gulp.dest('./dist/img'))
})
// html压缩
gulp.task('html', async() => {
await gulp.src('./app/*.html')
.pipe(htmlmin({ collapseWhitespace: true }))
.pipe(gulp.dest('dist/'))
.pipe(connect.reload())
});
gulp.task('clean', async() => {
await del(['dist/*']);
})
//服务
gulp.task('connect', function () {
connect.server({
root: "app",
port: 8080,
livereload: true,
});
});
//监视文件, 自动执行
gulp.task('myWatch', function(){
gulp.watch('./app/scss/*.scss', gulp.series('scss'))
gulp.watch('./app/css/*.css', gulp.series('css'))
gulp.watch('./app/js/*.js', gulp.series('js'))
gulp.watch('./app/index.html', gulp.series('html'))
gulp.watch('./app/img/*', gulp.series('img'))
})
//问题,修改引入文件打包之后单独执行一次
gulp.task('rev', async () => {
await gulp.src(['./dist/rev/*.json', './dist/*.html'])
.pipe(revCollector({replaceReved:true}))
.pipe(gulp.dest('./dist'));
})
//启动开发 gulp.series是顺序执行 gulp.parallel是同步执行
gulp.task('start', gulp.series(gulp.parallel('myWatch', 'connect')));
// 构建项目
gulp.task('dist',gulp.series('clean',gulp.parallel('html','scss', 'css', 'js', 'img')));
页面结构
html
var fileinclude = require('gulp-file-include'); gulp.task('file', function () { gulp.src('./*.html') .pipe(fileinclude({ prefix: '@@@', basepath: '@file' })) .pipe(gulp.dest('dist')); });
页面中
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<header>
@@@include('./dd/header.html')
</header>
</body>
</html>