一直以来,我司的前端都是用 php 的 include 函数来实现引入 header 、footer 这些公用代码的,就像下面这样:javascript
<!-- 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,这就让我碰到难题了。php
若是是小项目,那就直接手动多复制粘贴几遍,但若是页面较多,复制粘贴的方案明显不靠谱,维护成本也高。html
在查了不少资料后,最终肯定用 gulp 来解决,具体操做以下:前端
首先新建个文件夹,在终端里定位到文件夹的位置,而后进行 npm 初始化java
npm initgit
而后安装 gulpgithub
npm install gulp --save-devweb
接着安装 gulp-file-includenpm
npm install gulp-file-include --save-devjson
接着咱们手动新建一个 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')); });
项目的总体目录结构应该是这样
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>
在终端里敲入如下代码,看执行效果
gulp fileinclude
会发现,多了个 dist 文件夹,里面有一个 index.html 文件,gulp-file-include 已经帮咱们把最终编译好的 index.html 文件生成好了。
可能你已经能触类旁通了,在 gulpfile.js 里,咱们能够手动设置最终生成文件的位置,就是这句话
gulp.dest('dist')
静态页面引入公用代码的问题已经解决了,但每次编写源 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 静态页面的头部和底部都是相同的,如何让每一个页面统一调用一个公共的头部和底部呢?