Viteでvite-plugin-handlebarsを使用してHTMLパーツを読み込む
Viteにてエントリーポイント先の.html
の中でパーツ単位で分けられたhtmlファイルを読み込みたい場合は、vite-plugin-handlebarsを使用するとスマートに実現出来ます。
例えば普段EJSなどを使用しているとヘッダーは_header.ejs
、フッターは_footer.ejs
で切り出しそれぞれをindex.ejs
にてinclude()
すると思いますが、これと同じことが出来るようになります。
install
まずはインストールします。
yarn add -D vite-plugin-handlebars
プラグインをvite.configに追加
vite.config.ts
import react from '@vitejs/plugin-react'
import { resolve } from 'path'
import { defineConfig, UserConfig } from 'vite'
+ import handlebars from 'vite-plugin-handlebars'
// isProduction
const isProduction = process.env.NODE_ENV === 'production'
// https://vitejs.dev/config/
const config: UserConfig = {
plugins: [
react(),
+ handlebars({
+ partialDirectory: resolve(__dirname, './src/html-partials'),
+ context: {
+ isProduction: isProduction
+ },
+ reloadOnPartialChange: false
+ }),
]
}
export default defineConfig(config)
context
の部分に色々と値を持たせる事が出来るので、この辺りを上手いこと活用できればViteでも楽にhtmlを扱うことが出来そうです。
contextの仕様: https://github.com/alexlafroscia/vite-plugin-handlebars#defining-context
一旦上記では何かと使うであろうisProduction
のみ持たせています。
htmlパーツを読み込む
partialDirectory
で指定したディレクトリ配下のhtmlファイルを自由に読み込むことが出来るので、例えばsrc/html-partials/_header.html
を読み込みたい場合はファイル名をそのまま指定しれあげればOKです。
index.html
<!DOCTYPE html>
<html lang="ja">
<body>
{{> _header }}
<main id="app"></main>
<script type="module" src="./main.tsx"></script>
</body>
</html>
contextに持たせたisProduction
を用いて例えばビルド時のみGTMタグを出力したい場合も容易に実現出来ます。
index.html
<head>
{{#if isProduction}}
<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXXXXX');</script>
<!-- End Google Tag Manager -->
{{/if}}
</head>
Viteに限らず静的なWeb制作をしようとするとhtmlファイルを切り出してパーツ毎に分けた開発を行う事も多いですので、Viteの場合はvite-plugin-handlebarsなどの便利なプラグインを活用してみると良さそうです。