gulp-file-include 是 gulp 插件,它提供了一個 include 方法讓我們可以像后端模板那樣把公共部分的頁面導入進來。
安裝依賴包(包括了 gulp-file-include 和 del)
npm install --save-dev gulp-file-include del
項目結構目錄
修改 gulpfile.js,結合 browser-sync 一起使用
'use strict'; var gulp = require('gulp'), del = require('del'), fileinclude = require('gulp-file-include'), browserSync = require('browser-sync').create(); // 清除 dist 文件夾 gulp.task('clean', function () { return del.sync('./app/dist'); }); // html 整合 gulp.task('html', function () { return gulp.src('./app/src/template/*.html') .pipe(fileinclude()) .pipe(gulp.dest('./app/dist')); }); // 配置服務器 gulp.task('serve', function () { browserSync.init({ server: { baseDir: './app/dist' }, port: 8000 }); // 監聽 html gulp.watch('./app/src/template/**/*.html', ['html']).on('change', browserSync.reload);
});
gulp.task('default', ['clean', 'html', 'serve']);
html:
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> @@include('inc/header.html', {"title": "home"}) <p></p> </body> </html>
header.html:
<h1>@@title</h1>
打包:
gulp
瀏覽器會自動打開頁面 http://localhost:8000,顯示 home。在 dist 文件夾中查看 index.html:
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <h1>home</h1> <p></p> </body> </html>
當然,gulp-file-include 還有很多強大的功能,具體內容可以參考官網,這里我就不多說了。