gulp

新建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')));

 頁面結構javascript

 

htmlcss

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>html

相關文章
相關標籤/搜索