前端引用公共html模块方案

2023-05-16

最近临时一个负责公司官网的妹纸请假,于是临时接手了下官网的项目,官网都是静态页面,算是很简单的,但发现页面挺多,而每个页面总有部分是和其他页面一模一样的,比如页头、页尾等,这样就导致一个地方的修改要在其他N个页面手动重复的改下,当然,这是我无法忍受的,于是思考下怎样将公用的部分独立出来供调用。

开始想直接用js异步请求一个公用模块的页面即可,但考虑到官网的SEO问题,就放弃了,接着就想能否用webpack将代码分为开发环境和生产环境,在开发环境进行页面的拼接,完成后输出到生产环境,这样就不会影响seo,同时还能借助webpack的强大打包功能将资源进行打包压缩等处理,下面简要阐述demo的搭建。

demo的整体结构如下:


base-config
   --webpack.dir-foreach.config.js
css
images
js
lib
publicLayout
   --main.js
publish
templateSource
   --commonhtml
   --course
    --course.ejs
    --course.js
   --index
    --index.ejs
    --index.js
   .........
package.json
webpack.build.config.js
webpack.config.js

 主要的构建模块实在publicLayout和templateSource两个目录:

publicLayout: 主要封装公共模块的引用模块,main.js代码如下:


const header = require('../templateSource/commonhtml/header.html');  //引入公共页面头
const topbar = require('../templateSource/commonhtml/topbar.html');  //引入body中存在的公共模块
const footer = require('../templateSource/commonhtml/footer.html');  //引入公页面脚
const htmlconfig = {
    header: header,
    topbar: topbar,
    footer: footer
};
module.exports = htmlconfig;  //导出供调用

templateSource: 存放页面的构建模板,此demo中采用ejs作为前端模板,如index页,由index.ejs生成:


 1 <%= header %>
 2     <link type="text/css" rel="stylesheet" href="css/course.css">
 3 </head>
 4 <body>
 7     <div class="nav-bar">
 9         <div class="nav">
10             <ul class="navigation">
11                 <li>
12                     <a href="index.html" target="_self" title="">首页</a>
13                 </li>
14                 <li>
15                     <a href="course.html" target="_self" title="" class="cur">课程定制</a>
16                 </li>
17                 ......
18             </ul>
20         </div>
22     </div>
24     <!-- wrapper -->
25     <div id="container">
26         <div>主内容部分1</div>
27         <%= topbar %>
28         <div>主内容部分2</div>
29     </div>
30     <!-- footer -->
31     <%= footer %>
32 </body>
33 </html>  

<%= header %>即是引入main.js中封装的公共头部分,与当前的html完成拼接,最终输出到发布环境(publish)中。
index.js代码如下:

const publiclayout = require('../../publicLayout/main.js');  //总是引入封装的页面公共部分
const mainindex = require('./index.ejs');  //引入当前页的模板模块
module.exports = mainindex(publiclayout);  //将公共部分的多个变量导出到页面模板中进行页面拼接

整个demo相对简单,仅仅是为了规避在多个页面中修改同一处的重复劳动这一痛点。

详细的项目脚手架可前往GitHub查看:https://github.com/frankshin/public-html-layout

ps:后续脚手架会阶段性升级,加入新功能,所以本文中涉及代码的部分具体还是以github中的为准

 

转载于:https://www.cnblogs.com/xudengwei/p/6459136.html

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

前端引用公共html模块方案 的相关文章

随机推荐