LoginSignup
7
5

More than 5 years have passed since last update.

webpackを使ってhtmlをテンプレートとして利用する

Posted at

サイトをhtmlで作るときに
ヘッダー、フッター等の共通するパーツを
ぺージごとに静的に埋め込むのがめんどくさい…

と思いhtmlのままでテンプレートとして使う方法がないか調べて実際に導入した方法です。

実行環境

webpack 4.28.2

使用したパッケージ

HTML Loader
https://github.com/webpack-contrib/html-loader
※今回はインストールしたhtml-loaderのバージョンは^0.5.5です。

インストール

npm i -D html-loader

ソース

ディレクトリ

root/
┗ src/
 ┣ template/
 ┃ ┗ header.html
 index.html

テンプレートとして扱うファイル

header.html
<header>
    <nav>
        <ul>
            <li>menu1</li>
            <li>menu2</li>
            <li>menu3</li>
        </ul>
    </nav>
</header>

テンプレートを読み込むファイル

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
<%= require('html-loader!./template/header.html') %>
<main>
    <p>メインコンテンツ</p>
</main>
</body>
</html>

<%= require('html-loader!以降のパスはファイルごとに調整してください。

これだけでwebpackのmodedevelopのときでもproductionでも
header.htmlの内容をindex.htmlに読み込むことができました!
webpack環境でhtmlサイトを作成する際には
共通部分を気軽に扱えるので積極的に取り入れたい方法だと感じました。

7
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
5