標籤:container 方案 web lin 部分 logs 建模 styles div
最近臨時一個負責公司官網的妹紙請假,於是臨時接手了下官網的項目,官網都是靜態頁面,算是很簡單的,但發現頁面挺多,而每個頁面總有部分是和其他頁面一模一樣的,比如頁頭、頁尾等,這樣就導致一個地方的修改要在其他N個頁面手動重複的改下,當然,這是我無法忍受的,於是思考下怎樣將公用的部分獨立出來供調用。
開始想直接用js非同步請求一個公用模組的頁面即可,但考慮到官網的SEO問題,就放棄了,接著就想能否用webpack將代碼分為開發環境和生產環境,在開發環境進行頁面的拼接,完成後輸出到生產環境,這樣就不會影響seo,同時還能藉助webpack的強大打包功能將資源進行打包壓縮等處理,下面簡要闡述demo的搭建。
demo的整體結構如下:
1 base-config 2 --webpack.dir-foreach.config.js 3 css 4 images 5 js 6 lib 7 publicLayout
--main.js 8 publish 9 templateSource
--commonhtml
--course
--course.ejs
--course.js
--index
--index.ejs
--index.js
.........10 package.json11 webpack.build.config.js12 webpack.config.js
主要的構建模組實在publicLayout和templateSource兩個目錄:
publicLayout: 主要封裝公用模組的引用模組,main.js代碼如下:
1 const header = require(‘../templateSource/commonhtml/header.html‘); //引入公用頁面頭2 const topbar = require(‘../templateSource/commonhtml/topbar.html‘); //引入body中存在的公用模組3 const footer = require(‘../templateSource/commonhtml/footer.html‘); //引入公頁面腳4 const htmlconfig = {5 header: header,6 topbar: topbar,7 footer: footer8 };9 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代碼如下:
1 const publiclayout = require(‘../../publicLayout/main.js‘); //總是引入封裝的頁面公用部分2 const mainindex = require(‘./index.ejs‘); //引入當前頁的模板模組3 module.exports = mainindex(publiclayout); //將公用部分的多個變數匯出到頁面模板中進行頁面拼接
整個demo相對簡單,僅僅是為了規避在多個頁面中修改同一處的重複勞動這一痛點。
GitHub:https://github.com/frankshin/public-html-layout
前端引用公用html模組方案探索