首页 > 语言 > JavaScript > 正文

静态页面实现 include 引入公用代码的示例

2024-05-06 15:26:15
字体:
来源:转载
供稿:网友

一直以来,我司的前端都是用 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>            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选