ejs使用Gulp生成静态页面

gulpfile.js里添加var ejs require('gulp-ejs')

命令行中执行: npm install gulp-ejs

gulp.task('gulp-ejs', function(){

  gulp.src(模版目录 + '/**/*.html')
  .pipe(data(function (file) {
  var filePath = file.path;
    // global.json 全局数据,页面中直接通过属性名调用
    return Object.assign(JSON.parse(fs.readFileSync(模版目录+ '/global.json')), {
      // local: 每个页面对应的数据,页面中通过 local.属性 调用
      local: JSON.parse(fs.readFileSync( path.join(path.dirname(filePath), path.basename(filePath, '.html') + '.json')))
    })
  }))
  .pipe(ejs().on('error', function(err) {
    gutil.log(err);
    this.emit('end');
  }))
  .pipe(gulp.dest(生成目录));
});

目录结构

1._golobal文件下的head.ejs

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title><%= local.title %></title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="renderer" content="webkit">
<link rel="shortcut icon" href="网站图标路径"/>
<% styles.forEach(function(sty){ %>

<link rel="stylesheet" href="<%= sty %>">

<% }) %>

上面引用公用css下面引用单独页面css样式

<%
if(local.styles) {
local.styles.forEach(function(sty){ %>

<link rel="stylesheet" href="<%= sty %>">

<% })

}
%>
</head>

2._golobal文件下的foot.ejs

<% scripts.forEach(function(js){ %>

<script src="<%= js %>"></script>

<% }) %>

上面引用公用js下面引用单独页面js样式
<%
if(local.scripts) {
local.scripts.forEach(function(js){ %>

<script src="<%= js %>"></script>

<% })
}
%>

3.global.json公用js跟css

{
  "_ImgUrl":"页面公用图片路径",
  "styles": [
    "/PubCss/base.min.css"
  ],
  "scripts": [
    "/framework/common/jquery-1.9.1.min.js"
  ]
}

4.goodsList文件下goodsList.html

<%- include('../../_global/head') %>  (引用css)

<body>

<%- include('../../_partial/header') %>(引用公共头部)

<%- include('../../_partial/goodsList') %>(引用单独页面内容)

<%- include('../../_partial/footer') %>(引用公共页尾)

<%- include('../../_global/foot') %>(引用js)

</body>
</html>

4.goodsList文件下goodsList.json

{
  "title": "个人中心",
  "styles": [
    "个人中心css样式"
  ],
  "scripts": [
    "个人中心js样式"
  ]
}

原文地址:https://www.cnblogs.com/CMing/p/6722392.html