이 레슨에서 배우는 것
- CLI 옵션으로 원하는 조건의 리포트 만들기
- Node API로 여러 페이지를 반복 측정하고 결과 정리하기
- 로그인·클릭이 필요한 화면을 사용자 흐름으로 측정하기
설치
# Node.js 18 이상 + Chrome(또는 Chromium) 필요
npm install -g lighthouse
lighthouse --version
# 설치 없이
npx lighthouse https://testforge.kr/ --view--view는 측정이 끝나면 HTML 리포트를 브라우저로 엽니다. 기본 설정은 DevTools의 Mobile·Navigation과 같습니다.
자주 쓰는 옵션
lighthouse https://testforge.kr/ \
--output html --output json \
--output-path ./reports/home \
--only-categories=performance,accessibility \
--preset=desktop \
--chrome-flags="--headless=new" \
--quiet
# → reports/home.report.html, reports/home.report.json| 옵션 | 의미 |
|---|---|
--output, --output-path | html · json · csv. 여러 번 쓰면 형식마다 파일이 생김 |
--only-categories | 측정할 범주만(performance, accessibility, best-practices, seo). 시간 단축 |
--only-audits / --skip-audits | 특정 항목만 실행하거나 제외 |
--preset=desktop | 데스크톱 화면·스로틀링 설정 |
--throttling-method | simulate(기본, 빠른 네트워크에서 측정 후 느린 조건을 계산) · devtools(실제로 느리게 만듦) · provided(감속 없음) |
--chrome-flags | Chrome 실행 옵션. CI·서버에서는 --headless=new, 컨테이너에서는 --no-sandbox가 필요할 수 있음 |
--extra-headers | 요청 헤더 추가(JSON 문자열 또는 파일). 스테이징 인증 헤더 등 |
--blocked-url-patterns | 특정 URL 차단. 서드파티 스크립트 영향 비교 |
--locale=ko | 리포트 언어 |
JSON 결과 읽기
JSON 리포트(LHR, Lighthouse Result)에는 모든 값이 들어 있습니다. 점수는 0~1 사이 값입니다.
# jq로 점수와 주요 지표 꺼내기
jq '{
performance: .categories.performance.score,
lcp_ms: .audits["largest-contentful-paint"].numericValue,
tbt_ms: .audits["total-blocking-time"].numericValue,
cls: .audits["cumulative-layout-shift"].numericValue
}' reports/home.report.jsonNode API로 여러 페이지 측정
import fs from 'node:fs';
import lighthouse from 'lighthouse';
import * as chromeLauncher from 'chrome-launcher';
const pages = ['/', '/tools/', '/tools/k6/'];
const base = 'https://testforge.kr';
const RUNS = 3;
const chrome = await chromeLauncher.launch({ chromeFlags: ['--headless=new'] });
const rows = [];
try {
for (const p of pages) {
const results = [];
for (let i = 0; i < RUNS; i++) {
const { lhr } = await lighthouse(base + p, {
port: chrome.port,
onlyCategories: ['performance'],
output: 'json',
logLevel: 'error',
});
results.push({
score: Math.round(lhr.categories.performance.score * 100),
lcp: Math.round(lhr.audits['largest-contentful-paint'].numericValue),
tbt: Math.round(lhr.audits['total-blocking-time'].numericValue),
cls: lhr.audits['cumulative-layout-shift'].numericValue,
});
}
results.sort((a, b) => a.score - b.score);
rows.push({ page: p, ...results[Math.floor(RUNS / 2)] }); // 중앙값
}
} finally {
await chrome.kill();
}
console.table(rows);
fs.writeFileSync('lighthouse-summary.json', JSON.stringify(rows, null, 2));npm install lighthouse chrome-launcher
node measure.mjs세 번째 인자로 설정 객체를 넘길 수 있습니다. 예: lighthouse(url, flags, { extends: 'lighthouse:default', settings: { formFactor: 'desktop', screenEmulation: { disabled: true } } }).
로그인한 화면 측정하기
Lighthouse는 기본적으로 측정 전에 쿠키·저장소를 지웁니다. 로그인 상태를 유지하려면 Puppeteer로 먼저 로그인하고, 같은 브라우저에서 저장소 초기화를 끈 채 측정합니다.
import puppeteer from 'puppeteer';
import lighthouse from 'lighthouse';
const browser = await puppeteer.launch({ headless: true });
const page = await browser.newPage();
// 1) 로그인
await page.goto('http://localhost:5173/login');
await page.type('#email', 'tester@example.com');
await page.type('#password', process.env.TEST_PASSWORD);
await Promise.all([page.waitForNavigation(), page.click('button[type=submit]')]);
// 2) 같은 페이지 객체로 측정 — 저장소를 지우지 않음
const { lhr } = await lighthouse('http://localhost:5173/dashboard',
{ disableStorageReset: true, onlyCategories: ['performance'] }, undefined, page);
console.log('dashboard performance:', lhr.categories.performance.score * 100);
await browser.close();사용자 흐름 (user flows)
"상품 목록 → 필터 클릭 → 상세 페이지"처럼 여러 단계를 한 리포트로 측정하려면 사용자 흐름을 씁니다. 1강의 세 가지 모드를 코드로 조합합니다.
import fs from 'node:fs';
import puppeteer from 'puppeteer';
import { startFlow } from 'lighthouse';
const browser = await puppeteer.launch();
const page = await browser.newPage();
const flow = await startFlow(page, { name: '도구 찾기 흐름' });
// 1) 첫 방문 로딩
await flow.navigate('https://testforge.kr/');
// 2) 상호작용 구간 — INP·CLS가 측정됨
await flow.startTimespan({ name: '분류 펼치기와 검색' });
await page.click('.nav-tools-toggle');
await page.type('#global-search', 'k6');
await new Promise((r) => setTimeout(r, 1500));
await flow.endTimespan();
// 3) 현재 화면 상태 점검 — 접근성 등
await flow.snapshot({ name: '검색 결과 표시 상태' });
// 4) 클릭으로 이동하는 페이지 로딩 (SPA 라우팅 포함)
await flow.navigate(async () => { await page.click('a[href="/tools/k6/"]'); }, { name: 'k6 가이드로 이동' });
fs.writeFileSync('flow-report.html', await flow.generateReport());
await browser.close();흐름 리포트는 단계별 요약과 각 단계의 상세 리포트를 함께 보여 줍니다. Chrome DevTools의 Recorder 패널에서 클릭 과정을 녹화해 Puppeteer 스크립트로 내보낸 뒤, 그 안에 흐름 단계를 끼워 넣으면 빠르게 만들 수 있습니다. Playwright를 쓰는 팀은 커뮤니티 패키지(playwright-lighthouse)로 비슷하게 연동할 수 있습니다.
정리
- CLI로 출력 형식·범주·프리셋·스로틀링을 정해 측정하고, JSON 리포트에서 점수(0~1)와 지표 값을 꺼냅니다.
- Node API + chrome-launcher로 여러 페이지를 여러 번 측정해 중앙값을 기록합니다.
- 로그인 화면은 Puppeteer로 로그인한 뒤
disableStorageReset으로 측정합니다. - 사용자 흐름은 navigate·timespan·snapshot을 조합해 여러 단계와 상호작용(INP)을 한 리포트로 측정합니다.