简单的组件化开发(一)

gulp-file-include提供了一个include的方法让我们可以想后端模版一样把公共的部分分离出去。

方法如下:

  1. 安装node.js
  2. 安装淘宝镜像
  3. 全局安装gulp   cnpm i -g gulp
  4. 项目目录下安装 gulp  cnpm gulp
  5. 安装gulp-file-include,cnpm install gulp-file-clude

目录结构如下

 

gulp.file配置

var gulp = require('gulp');
var fileinclude = require('gulp-file-include');
var ejs = require('gulp-ejs');

gulp.task('fileinclude',function(){
    gulp.src('src/**.html')
    .pipe(fileinclude({
        prefix:'@@',
        basepath:'@file',
        context: {
            arr: ['test1', 'test2']
          }
    }))
    .pipe(gulp.dest('dist'))
})

gulp.task('ejs',function(){
    gulp.src('src/**.ejs')
    .pipe(ejs({}, { ext: '.html' }))
    .pipe(gulp.dest('dist'));
})

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')
    <p>这是内容</p>
    @@include('include/footer.html',{
        "footer1": "home-footer1",  
        "footer2": "home-footer2",  
        "footer": {  
            "footer1": "home-footer-footer1",  
            "footer2": "home-footer-footer2"  
        }
    })
    <ul>
        @@for (var i = 0; i < arr.length; i++) {
          <li>`+arr[i]+`</li>
        }
    </ul>
    @@loop('include/loop.html',[
    { "title": "My post title", "text": "<p>lorem ipsum...</p>" },
    { "title": "Another post", "text": "<p>lorem ipsum...</p>" },
    { "title": "One more post", "text": "<p>lorem ipsum...</p>" }
    ])
    @@loop('include/loop.html','json/data.json')
</body>
</html>

header.html

<h1>我是头部</h1>
<h2>我也是头部</h2>

footer.html

<h1>我是底部</h1>
<h2>@@footer1</h2>
<h2>@@footer2</h2>
<h2>@@footer.footer1</h2>
<h2>@@footer.footer2 </h2>

loop.html

<article>
    <h1>@@title</h1>
    @@text
</article>

 

data.json

[
    { "title": "My post title", "text": "<p>lorem ipsum...</p>" },
    { "title": "Another post", "text": "<p>lorem ipsum...</p>" },
    { "title": "One more post", "text": "<p>lorem ipsum...</p>" }
  ]

 

转载于:https://www.cnblogs.com/oldcoder/p/8432967.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值