最近臨時一個負責公司官網的妹紙請假,於是臨時接手了下官網的項目,官網都是靜態頁面,算是很簡單的,但發現頁面挺多,而每個頁面總有部分是和其他頁面一模一樣的,比如頁頭、頁尾等,這樣就導致一個地方的修改要在其他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中的為准
