靜態頁面如何? include 引入公用代碼,靜態頁面include
一直以來,我司的前端都是用 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>4、運行
在終端裡敲入以下代碼,看執行效果
gulp fileinclude
會發現,多了個 dist 檔案夾,裡面有一個 index.html 檔案,gulp-file-include 已經幫我們把最終編譯好的 index.html 檔案產生好了。
可能你已經能舉一反三了,在 gulpfile.js 裡,我們可以手動設定最終組建檔案的位置,就是這句話
gulp.dest('dist')
5、自動編譯
靜態頁面引入公用代碼的問題已經解決了,但每次編寫源 html 後,都要去終端裏手動執行下編譯操作還是很麻煩,那能不能讓檔案自動編譯呢?答案一定是可以的。
gulp 有個 watch 方法,就是監聽檔案是否有變動的,我們只需稍微修改下 gulpfile.js 檔案,增加一段監聽代碼,如下:
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'));});gulp.task('watch', function () { gulp.watch('page/**/*.html', ['fileinclude']);});
寫好之後,我們只需在終端裡執行
gulp watch
我們每次儲存源 html 後,gulp 就會自動幫我們編譯一遍。
至此,靜態頁面如何? include 引入公用代碼的問題,順利解決,最後附上相關資料。
附:
HTML 靜態頁面的頭部和底部都是相同的,如何讓每個頁面統一調用一個公用的頭部和底部呢?
靜態html如何包括header和footer ?
靜態頁面Demo項目,如何將header和footer 像PHP一樣 include?
grunt-html-imports