1.1.2 • Published 4 months ago

hmr-monitor v1.1.2

Weekly downloads
-
License
MIT
Repository
-
Last release
4 months ago

hmr-monitor

npm version license React Next.js Webpack

React 및 Next.js 애플리케이션을 위한 HMR 성능 모니터링 솔루션


📌 개요

hmr-monitor는 React 애플리케이션의 HMR(Hot Module Replacement) 과정에서 컴포넌트의 렌더링 성능과 번들 크기 변화를 실시간으로 추적합니다. 개발자에게 즉각적인 성능 피드백을 제공하여 최적화 작업을 돕습니다.


✨ 주요 기능

  • 🔍 정확한 측정: React Profiler API를 통한 정확한 렌더링 시간 측정
  • 📊 실시간 분석: 컴포넌트 변경 시 즉시 성능 영향 분석
  • 📦 번들 크기 모니터링: 코드 변경이 번들 크기에 미치는 영향 추적
  • 🔄 손쉬운 통합: React, Next.js와 원활한 통합
  • 🛠️ 다양한 설정: 여러 모니터링 옵션 및 출력 형식 커스터마이징
  • 🧩 다중 모듈 지원: ESM, CommonJS, UMD 형식 모두 지원

🚀 설치 방법

# npm 사용
npm install --save-dev hmr-monitor

# yarn 사용
yarn add -D hmr-monitor

# pnpm 사용
pnpm add -D hmr-monitor

📋 사용 방법

React + Webpack 프로젝트

// webpack.config.js
const { HMRMonitorPlugin } = require("hmr-monitor");

module.exports = {
  // 기존 설정...
  plugins: [
    // 다른 플러그인들...
    new HMRMonitorPlugin({
      // 옵션 (자세한 내용은 아래 참조)
      useReactProfiler: true,
      logToConsole: true,
    }),
  ],
};

Next.js 프로젝트

// next.config.mjs
import { withHMRMonitor } from "hmr-monitor";

export default withHMRMonitor(
  {
    // 기존 Next.js 설정...
  },
  {
    verbose: true,
  }
);

ESM 환경에서 사용하기

import { HMRMonitorPlugin, withHMRMonitor } from "hmr-monitor";

// Webpack 플러그인으로 사용
new HMRMonitorPlugin({
  /* 옵션 */
});

// 또는 Next.js 설정으로 사용
export default withHMRMonitor({
  /* Next.js 설정 */
});

🌟 React Profiler API 활용 방법

방법 1: 전체 앱 활성화

애플리케이션 진입점에 다음 코드를 추가합니다:

// src/index.js 또는 pages/_app.js
import { setupReactProfiler } from "hmr-monitor";

// React 앱 초기화 이후 호출
setupReactProfiler();

// 일반적인 React 앱 렌더링 코드...

방법 2: Babel 플러그인 활용 (권장)

모든 컴포넌트를 자동으로 Profiler로 래핑합니다:

// babel.config.js
module.exports = {
  presets: ["@babel/preset-react"],
  plugins: [
    [
      "hmr-monitor/babel-plugin-react-profiler",
      {
        include: ["src/components/**/*.jsx"],
        exclude: ["**/node_modules/**"],
      },
    ],
  ],
};

방법 3: 수동 컴포넌트 래핑

import React from "react";
import { createProfilerWrapper } from "hmr-monitor";

// withProfiler HOC 생성
const withProfiler = createProfilerWrapper(React);

// 컴포넌트 정의
function ProductCard(props) {
  return (
    <div className="product-card">
      <h2>{props.name}</h2>
      <p>{props.price}</p>
    </div>
  );
}

// Profiler로 래핑하여 내보내기
export default withProfiler(ProductCard, "ProductCard");

방법 4: React.Profiler 직접 사용

import React from "react";

function App() {
  const handleRender = (id, phase, actualDuration) => {
    // 전역 HMR 모니터에 측정값 기록
    if (window.__HMR_MONITOR__) {
      window.__HMR_MONITOR__.registerProfilerMeasurement(id, actualDuration);
    }
  };

  return (
    <React.Profiler id="RootApp" onRender={handleRender}>
      <div className="app">{/* 애플리케이션 컨텐츠 */}</div>
    </React.Profiler>
  );
}

📈 출력 결과 예시

HMR 업데이트 시 터미널에 다음과 같은 정보가 표시됩니다:

[HMR-Monitor] 컴포넌트: ProductCard.jsx
├─ 렌더링 시간: 8.42ms (이전: 12.56ms, -4.14ms 개선)
└─ 번들 크기: 12.4KB (+0.8KB 증가)

⚙️ 옵션 설정

옵션타입기본값설명
enabledbooleantrue모니터링 활성화 여부
logToConsolebooleantrue콘솔에 결과 출력 여부
useReactProfilerbooleantrueReact Profiler API 사용 여부
minSizeDiffnumber10보고할 최소 크기 변화 (바이트)
renderTimeFormatfunction-렌더링 시간 출력 포맷 커스터마이징
bundleSizeFormatfunction-번들 크기 출력 포맷 커스터마이징
componentFilterfunction-모니터링할 컴포넌트 필터링 함수
colorsobject-출력 텍스트 색상 커스터마이징

예시 설정:

new HMRMonitorPlugin({
  // 기본 설정
  enabled: true,
  logToConsole: true,
  useReactProfiler: true,

  // 특정 컴포넌트만 필터링
  componentFilter: (name) => name.includes("Card"),

  // 포맷 커스터마이징
  renderTimeFormat: (current, previous) => {
    const diff = previous ? current - previous : 0;
    return `${current.toFixed(2)}ms (${Math.abs(diff).toFixed(2)}ms ${
      diff < 0 ? "개선" : "증가"
    })`;
  },
});

🔍 측정 방식

hmr-monitor는 다음 순서로 렌더링 시간을 측정합니다:

  1. React Profiler API - 가장 정확한 측정 방식
  2. React DevTools API - 개발자 도구 활용
  3. Performance API - 브라우저 성능 API 활용
  4. 폴백 방식 - 다른 방법이 실패한 경우

최상의 결과를 위해 React Profiler API를 직접 활성화하거나 Babel 플러그인을 사용하는 것을 권장합니다.


💻 브라우저 호환성

  • 모든 최신 브라우저 (Chrome, Firefox, Safari, Edge)
  • IE11 (ES5 호환)
  • Node.js 12.0.0 이상

🔧 트러블슈팅

측정값이 표시되지 않는 경우

  • React 16.9 이상 버전을 사용하고 있는지 확인하세요.
  • 개발 모드에서 실행 중인지 확인하세요.
  • HMR이 올바르게 구성되어 있는지 확인하세요.

부정확한 측정값

  • React DevTools가 설치되어 있으면 측정 정확도가 향상됩니다.
  • Babel 플러그인을 사용하면 가장 정확한 측정이 가능합니다.

📚 API 참조

주요 함수

  • HMRMonitorPlugin - Webpack 플러그인
  • withHMRMonitor - Next.js 통합용 래퍼
  • setupReactProfiler - DOM 기반 모니터링 설정
  • createProfilerWrapper - HOC 생성 유틸리티
  • measureReactRenderTime - 수동 성능 측정 도구

📄 라이센스

ISC

1.1.2

4 months ago

1.1.1

4 months ago

1.1.0

4 months ago

1.0.9

4 months ago

1.0.8

4 months ago

1.0.7

4 months ago

1.0.6

4 months ago

1.0.5

4 months ago

1.0.4

4 months ago

1.0.3

4 months ago

1.0.2

4 months ago

1.0.1

4 months ago

1.0.0

4 months ago