简单的组件化开发(一)
gulp-file-include提供了一个include的方法让我们可以想后端模版一样把公共的部分分离出去。
方法如下:
- 安装node.js
- 安装淘宝镜像
- 全局安装gulp cnpm i -g gulp
- 项目目录下安装 gulp cnpm gulp
- 安装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>" } ]