Try   HackMD

Webpack Include 其他 HTML 檔案

在製作專案時,一定會有全站頁面共用的元件(像是 header, footer 等等),若今天碰到 header、footer 有調整需求,要一個個修改 html 檔光用想的就覺得辛苦,本次討論的是若專案並非使用前端框架來製作時該如何處理

安裝 html-loader

$ npm install --save-dev html-loader

專案目錄結構

├── README.md
├── package-lock.json
├── package.json
├── src
|  ├── include
|  |  ├── footer.html
|  |  └── header.html
|  ├── index.html
|  └── main.js
└── webpack.config.js

準備共用元件

/src/include/header.html

<header> <nav> <ul> <li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">News</a></li> <li><a href="#">Blog</a></li> </ul> </nav> </header>

/src/include/footer.html

<footer> Copyright © 2021 XXX. All rights reserved. </footer>

要加入共用元件的頁面

/src/index.html

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <%= require('html-loader!./include/header.html').default %> <main> 網站內容 </main> <%= require('html-loader!./include/footer.html').default %> </body> </html>

這邊會需要在 require() 後方加上 .default 否則在頁面上會顯示 [object Module]

結果


本文重點在如何使用 html-loader include 其他 html 檔,樣式的部分暫不另外做其他的設定

tags: webpack html-loader