UNPKG

vite-pug-static-builder

Version:

Vite + Pugを使用した静的サイトビルダー - 複数のPugファイルを静的HTMLとしてビルドするViteプラグイン

63 lines (62 loc) 2.11 kB
import fs from 'node:fs'; import path from 'node:path'; import { compileFile } from 'pug'; import { outputLog } from './utils.js'; /** * Vite用Pugビルドプラグイン * @param settings - ビルド設定 * @returns Viteプラグイン */ export const vitePluginPugBuild = (settings) => { const { options, locals } = settings ?? {}; const pugOptions = { pretty: true, ...options }; const pathMap = new Map(); let root = ''; return { name: 'vite-plugin-pug-build', enforce: 'pre', apply: 'build', configResolved(config) { root = config.root; }, resolveId(source) { const parsedPath = path.parse(source); if (parsedPath.ext !== '.pug') { return null; } const pathAsHtml = path.format({ dir: parsedPath.dir, name: parsedPath.name, ext: '.html', }); pathMap.set(pathAsHtml, source); return pathAsHtml; }, load(id) { if (path.extname(id) !== '.html') { return null; } try { // PugファイルのHTMLへの変換 if (pathMap.has(id)) { const pugPath = pathMap.get(id); const compiledTemplate = compileFile(pugPath, pugOptions); const html = compiledTemplate(locals); outputLog('info', 'compiled:', path.relative(root, pugPath)); return html; } // 既存のHTMLファイルの読み込み if (fs.existsSync(id)) { return fs.readFileSync(id, 'utf-8'); } } catch (error) { // エラーログの出力 const errorMessage = error instanceof Error ? error.message : String(error); outputLog('error', 'compilation failed:', id, errorMessage); throw error; } return null; }, }; };