Development: Claude Code 활용 가이드
development: Claude Code 활용. 실용적인 팁과 코드 예시를 포함합니다.
이미지최적화파이프라인で표시速度を劇的に改善
이미지はWeb페이지の転送量の大部分を占めます。Claude Code를 사용하여、自動的に이미지を최적화する파이프라인を구축すれば、手作業の負担なく성능を改善할 수 있습니다。
이미지変換スクリプトの구축
> sharp를 사용한이미지최적화スクリプト를 생성해줘。
> WebP・AVIF変換、リサイズ、メタ데이터삭제を자동화して。
// scripts/optimize-images.ts
import sharp from 'sharp';
import { globSync } from 'glob';
import { mkdirSync, existsSync } from 'fs';
import path from 'path';
interface ImageConfig {
widths: number[];
formats: ('webp' | 'avif' | 'jpg')[];
quality: Record<string, number>;
}
const config: ImageConfig = {
widths: [320, 640, 960, 1280, 1920],
formats: ['avif', 'webp', 'jpg'],
quality: { avif: 50, webp: 75, jpg: 80 },
};
async function optimizeImage(inputPath: string, outputDir: string) {
const name = path.basename(inputPath, path.extname(inputPath));
for (const format of config.formats) {
for (const width of config.widths) {
const outputPath = path.join(outputDir, `${name}-${width}w.${format}`);
await sharp(inputPath)
.resize(width, undefined, { withoutEnlargement: true })
.toFormat(format, { quality: config.quality[format] })
.toFile(outputPath);
}
}
}
async function main() {
const images = globSync('src/assets/images/**/*.{jpg,jpeg,png}');
const outputDir = 'public/images/optimized';
if (!existsSync(outputDir)) mkdirSync(outputDir, { recursive: true });
for (const img of images) {
console.log(`最適化中: ${img}`);
await optimizeImage(img, outputDir);
}
console.log(`✅ ${images.length}枚の画像を最適化しました`);
}
main();
반응형이미지컴포넌트
// components/OptimizedImage.tsx
interface OptimizedImageProps {
src: string;
alt: string;
widths?: number[];
sizes?: string;
className?: string;
loading?: 'lazy' | 'eager';
priority?: boolean;
}
export function OptimizedImage({
src,
alt,
widths = [320, 640, 960, 1280],
sizes = '(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 33vw',
className,
loading = 'lazy',
priority = false,
}: OptimizedImageProps) {
const baseName = src.replace(/\.(jpg|jpeg|png)$/, '');
const avifSrcSet = widths
.map(w => `/images/optimized/${baseName}-${w}w.avif ${w}w`)
.join(', ');
const webpSrcSet = widths
.map(w => `/images/optimized/${baseName}-${w}w.webp ${w}w`)
.join(', ');
const jpgSrcSet = widths
.map(w => `/images/optimized/${baseName}-${w}w.jpg ${w}w`)
.join(', ');
return (
<picture>
<source type="image/avif" srcSet={avifSrcSet} sizes={sizes} />
<source type="image/webp" srcSet={webpSrcSet} sizes={sizes} />
<img
src={`/images/optimized/${baseName}-960w.jpg`}
srcSet={jpgSrcSet}
sizes={sizes}
alt={alt}
loading={priority ? 'eager' : loading}
decoding={priority ? 'sync' : 'async'}
fetchPriority={priority ? 'high' : undefined}
className={className}
/>
</picture>
);
}
지연 로딩とプレースホルダー
// ぼかしプレースホルダー付き지연 로딩
function BlurImage({ src, alt, blurDataUrl }: {
src: string;
alt: string;
blurDataUrl: string;
}) {
const [loaded, setLoaded] = useState(false);
return (
<div className="relative overflow-hidden">
{/* ぼかしプレースホルダー */}
<img
src={blurDataUrl}
alt=""
aria-hidden="true"
className={`absolute inset-0 h-full w-full object-cover transition-opacity duration-300
${loaded ? 'opacity-0' : 'opacity-100'}`}
style={{ filter: 'blur(20px)', transform: 'scale(1.1)' }}
/>
{/* 本画像 */}
<img
src={src}
alt={alt}
loading="lazy"
onLoad={() => setLoaded(true)}
className={`h-full w-full object-cover transition-opacity duration-300
${loaded ? 'opacity-100' : 'opacity-0'}`}
/>
</div>
);
}
ぼかしプレースホルダーの생성
// scripts/generate-blur.ts
import sharp from 'sharp';
async function generateBlurDataUrl(imagePath: string): Promise<string> {
const buffer = await sharp(imagePath)
.resize(10, 10, { fit: 'inside' })
.blur()
.toBuffer();
return `data:image/jpeg;base64,${buffer.toString('base64')}`;
}
빌드파이프라인への組み込み
{
"scripts": {
"images": "tsx scripts/optimize-images.ts",
"images:blur": "tsx scripts/generate-blur.ts",
"prebuild": "npm run images && npm run images:blur",
"build": "astro build"
}
}
정리
이미지최적화は폰트최적화と並んで、표시速度改善に最も효과적인施策です。Claude Code를 활용하면 sharp 를 사용한変換スクリプトから반응형이미지컴포넌트まで一貫して구축할 수 있습니다。번들分析と組み合わせて、総合的な성능改善を進めましょう。이미지최적화의 상세 정보는web.dev Images Guide를 참고하세요.
#Claude Code
#image optimization
#WebP
#AVIF
#performance
Claude Code 워크플로우를 한 단계 업그레이드하세요
지금 바로 Claude Code에 복사해 쓸 수 있는 검증된 프롬프트 템플릿 50선.
M
이 글을 작성한 사람
Masa
Claude Code를 적극 활용하는 엔지니어. 10개 언어, 2,000페이지 이상의 테크 미디어 claudecode-lab.com을 운영 중.
관련 글
Advanced
Claude Code Agent SDK 입문 ― 자율 에이전트를 빠르게 구축하는 방법
Claude Code Agent SDK로 자율형 AI 에이전트를 구축하는 방법을 해설합니다. 설정부터 도구 정의, 멀티스텝 실행까지 실전 코드와 함께 소개합니다.
Advanced
Claude Code 컨텍스트 관리 테크닉 완전 가이드
Claude Code의 컨텍스트 윈도우를 최대한 활용하는 실전 테크닉을 해설합니다. 토큰 절약, 대화 분할, CLAUDE.md 활용법까지 소개합니다.
Advanced
Claude Code MCP Server 설정 및 실전 활용 가이드
Claude Code의 MCP Server 기능을 종합적으로 소개합니다. 외부 도구 연결, 서버 설정, 실전 통합 사례까지 한 번에 알아보세요.