一直以來,我司的前端都是用 php 的 include 函數來實現引入 header 、footer 這些公用代碼的,就像下面這樣:
<!-- index.php --> <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title></head><body> <?php include('header.php'); ?> <div>頁面主體部分</div> <?php include('footer.php'); ?></body></html><!-- header.php --><header>這是頭部</header>
<!-- footer.php --><footer>這是底部</footer>
直到最近某個項目需要做一個 webapp,是通過 HBuilder 將靜態頁面打包成 APP,這就讓我碰到難題了。
如果是小項目,那就直接手動多復制粘貼幾遍,但如果頁面較多,復制粘貼的方案明顯不靠譜,維護成本也高。
在查了很多資料后,最終確定用 gulp 來解決,具體操作如下:
1、安裝 gulp 和 gulp-file-include
首先新建個文件夾,在終端里定位到文件夾的位置,然后進行 npm 初始化
npm init
然后安裝 gulp
npm install gulp --save-dev
接著安裝 gulp-file-include
npm install gulp-file-include --save-dev
2、新建并配置 gulpfile.js
接著我們手動新建一個 js 文件取名為 gulpfile,并在里面寫入如下代碼:
var gulp = require('gulp');var fileinclude = require('gulp-file-include'); gulp.task('fileinclude', function () { // 適配page中所有文件夾下的所有html,排除page下的include文件夾中html gulp.src(['page/**/*.html', '!page/include/**.html']) .pipe(fileinclude({ prefix: '@@', basepath: '@file' })) .pipe(gulp.dest('dist'));});3、創建項目目錄結構,并添加測試代碼
項目的整體目錄結構應該是這樣
app page include header.html footer.html index.html gulpfile.js package.json
然后我們添加測試代碼,header.html 和 footer.html 沒太多好說的,主要是 index.html 要特別注意引入的方式,代碼如下:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title></head><body> @@include('include/header.html') <div>頁面主體部分</div> @@include('include/footer.html')</body></html>
新聞熱點
疑難解答
圖片精選