CRA 디폴트 파일 reportWebVitals ..!?

제이밍·2021년 10월 21일
7

Measuring Performance

CRA를 통해 리액트 프로젝트를 시작해봤다면 디폴트로 들어가있던 reportWebVitals 파일이 기본적으로 생성되는데요, 오늘은 이 파일의 역할에 대해 알아보겠습니다.


기본 세팅된 Index 파일에 써있는것 처럼 reportWebVitals() 에 console.log를 넣어주면 개발창을 통해 앱의 퍼포먼스시간들을 분석하여 object형태로 보여줍니다.

Web Vitals

Create React App에서 서드파티 라이브러리 Web Vitals

cra는 웹 퍼포먼스 측정도구로 web-vitals 라는 라이브러리를 사용합니다.
(google에서 사이트 경험 측정, 개선용)
Web Vitals를 통해 어떤 측정값이 계산되고 리턴되는지 볼까요?

위의 이미지와 같이 index 파일 reportWebVitals(console.log)에서 찍히는 값을 살펴볼게요

interface Metric {
  // metric(측정도구) 이름
  name: 'CLS' | 'FCP' | 'FID' | 'LCP' | 'TTFB';
  // 측정된 현재값 (값이 작을수록 빠른성능을 뜻합니다)
  value: number;
  //  현재 측정값(current value)과 최신 측정값(last-reported value) 차이
  //  첫번째 리포트에서 위 둘값은 항상 같습니다.
  delta: number;
  // 특정 측정도구를 나타대는 유니크한 ID 값으로 중복되는 값들을 관리할 때 사용된다.
  id: string;
  // 계산된 측정값들의 내용들이 배열로 나열 된다.
  // ex) PerformanceNavigationTiming, LargestContentfulPaint
  entries: (PerformanceEntry | FirstInputPolyfillEntry | NavigationTimingPolyfillEntry)[];
}

Sending results to analytics

사이트 성능 측정 엔드포인트 분석 결과를 실제 사용하는 사이트에 보낼 수 있습니다.

function sendToAnalytics(metric) {
  const body = JSON.stringify(metric);
  const url = 'https://example.com/analytics';

  // Use `navigator.sendBeacon()` if available, falling back to `fetch()`
  if (navigator.sendBeacon) {
    navigator.sendBeacon(url, body);
  } else {
    fetch(url, { body, method: 'POST', keepalive: true });
  }
}

reportWebVitals(sendToAnalytics);

만약 연동된 google Analytics 가 있다면 id값을 만들어 더욱 쉽게 설정 할 수 있습니다.

function sendToAnalytics({ id, name, value }) {
  ga('send', 'event', {
    eventCategory: 'Web Vitals',
    eventAction: name,
    eventValue: Math.round(name === 'CLS' ? value * 1000 : value), // values must be integers
    eventLabel: id, // id unique to current page load
    nonInteraction: true, // avoids affecting bounce rate
  });
}

reportWebVitals(sendToAnalytics);

Reference

https://create-react-app.dev/docs/measuring-performance/
https://github.com/GoogleChrome/web-vitals/#types

profile
모르는것은 그때그때 기록하기

1개의 댓글

comment-user-thumbnail
2022년 11월 11일

좋은 글 잘보고갑니다~

답글 달기