|
| 1 | +import { Plugin } from "vite"; |
| 2 | +import sharp from "sharp"; |
| 3 | +import { existsSync } from "fs"; |
| 4 | +import { join, dirname, extname, basename } from "path"; |
| 5 | +import { glob } from "glob"; |
| 6 | + |
| 7 | +interface ImageOptimizerOptions { |
| 8 | + /** |
| 9 | + * 이미지를 찾을 디렉토리 패턴 |
| 10 | + * @default "contents/posts/** /img/** /*.(jpg|jpeg|png)" |
| 11 | + */ |
| 12 | + sourcePattern?: string; |
| 13 | + |
| 14 | + /** |
| 15 | + * 생성할 이미지 포맷들 |
| 16 | + * @default ["webp", "jpeg"] |
| 17 | + */ |
| 18 | + formats?: ("webp" | "jpeg" | "avif")[]; |
| 19 | + |
| 20 | + /** |
| 21 | + * WebP 품질 (0-100) |
| 22 | + * @default 90 |
| 23 | + */ |
| 24 | + webpQuality?: number; |
| 25 | + |
| 26 | + /** |
| 27 | + * JPEG 품질 (0-100) |
| 28 | + * @default 90 |
| 29 | + */ |
| 30 | + jpegQuality?: number; |
| 31 | + |
| 32 | + /** |
| 33 | + * AVIF 품질 (0-100) |
| 34 | + * @default 90 |
| 35 | + */ |
| 36 | + avifQuality?: number; |
| 37 | +} |
| 38 | + |
| 39 | +/** |
| 40 | + * 이미지를 여러 포맷으로 변환합니다 |
| 41 | + */ |
| 42 | +async function convertImage( |
| 43 | + sourcePath: string, |
| 44 | + formats: ("webp" | "jpeg" | "avif")[], |
| 45 | + options: ImageOptimizerOptions, |
| 46 | +) { |
| 47 | + const ext = extname(sourcePath).toLowerCase(); |
| 48 | + const dir = dirname(sourcePath); |
| 49 | + const name = basename(sourcePath, ext); |
| 50 | + |
| 51 | + // 이미 최적화된 이미지는 스킵 |
| 52 | + if (formats.includes("webp" as any) && ext === ".webp") return; |
| 53 | + if (formats.includes("jpeg" as any) && [".jpg", ".jpeg"].includes(ext)) return; |
| 54 | + if (formats.includes("avif" as any) && ext === ".avif") return; |
| 55 | + |
| 56 | + const image = sharp(sourcePath); |
| 57 | + |
| 58 | + for (const format of formats) { |
| 59 | + const outputPath = join(dir, `${name}.${format}`); |
| 60 | + |
| 61 | + // 이미 변환된 파일이 있으면 스킵 |
| 62 | + if (existsSync(outputPath)) continue; |
| 63 | + |
| 64 | + try { |
| 65 | + if (format === "webp") { |
| 66 | + await image |
| 67 | + .clone() |
| 68 | + .webp({ quality: options.webpQuality || 80 }) |
| 69 | + .toFile(outputPath); |
| 70 | + console.log(`✅ WebP 생성: ${outputPath}`); |
| 71 | + } else if (format === "jpeg") { |
| 72 | + await image |
| 73 | + .clone() |
| 74 | + .jpeg({ quality: options.jpegQuality || 80 }) |
| 75 | + .toFile(outputPath); |
| 76 | + console.log(`✅ JPEG 생성: ${outputPath}`); |
| 77 | + } else if (format === "avif") { |
| 78 | + await image |
| 79 | + .clone() |
| 80 | + .avif({ quality: options.avifQuality || 70 }) |
| 81 | + .toFile(outputPath); |
| 82 | + console.log(`✅ AVIF 생성: ${outputPath}`); |
| 83 | + } |
| 84 | + } catch (error) { |
| 85 | + console.warn(`⚠️ 이미지 변환 실패 (${sourcePath}):`, error); |
| 86 | + } |
| 87 | + } |
| 88 | +} |
| 89 | + |
| 90 | +/** |
| 91 | + * 빌드 시점에 이미지를 최적화하는 Vite 플러그인 |
| 92 | + */ |
| 93 | +export function createImageOptimizerPlugin(options: ImageOptimizerOptions = {}): Plugin { |
| 94 | + const { |
| 95 | + sourcePattern = "contents/posts/**/img/**/*.{jpg,jpeg,png}", |
| 96 | + formats = ["webp", "jpeg"], |
| 97 | + } = options; |
| 98 | + |
| 99 | + return { |
| 100 | + name: "vitepress-image-optimizer", |
| 101 | + |
| 102 | + async buildStart() { |
| 103 | + console.log("🖼️ 이미지 최적화 시작..."); |
| 104 | + |
| 105 | + try { |
| 106 | + const imagePaths = await glob(sourcePattern, { |
| 107 | + cwd: process.cwd(), |
| 108 | + absolute: true, |
| 109 | + }); |
| 110 | + |
| 111 | + console.log(`📁 발견된 이미지: ${imagePaths.length}개`); |
| 112 | + |
| 113 | + for (const imagePath of imagePaths) { |
| 114 | + await convertImage(imagePath, formats, options); |
| 115 | + } |
| 116 | + |
| 117 | + console.log("✅ 이미지 최적화 완료!"); |
| 118 | + } catch (error) { |
| 119 | + console.error("❌ 이미지 최적화 실패:", error); |
| 120 | + } |
| 121 | + }, |
| 122 | + }; |
| 123 | +} |
0 commit comments