# npm 사용법

## npm을 통해 Pushwoosh 웹 푸시 SDK 설치

npm을 사용하여 프로젝트에 Pushwoosh 웹 푸시 알림 SDK를 설치하고 사용하는 방법입니다.
이 가이드는 npm 및 JavaScript 모듈 가져오기에 대한 기본적인 이해가 있다고 가정합니다.

### SDK 설치:

```bash title="Pushwoosh 웹 푸시 알림 SDK 설치"
npm install web-push-notifications
```

<Aside type="caution" title="SDK 버전 관리에 대한 중요 참고 사항 (v3.45.0 이상)">
  버전 **3.45.0**부터 Pushwoosh 웹 SDK는 핵심 SDK 및 UI 위젯을 가져오는 모듈식 접근 방식을 도입했습니다.

  - **별도 가져오기:** 이제 주요 `Pushwoosh` 클래스와 원하는 위젯(예: `PWSubscriptionButtonWidget`, `PWSubscribePopupWidget` 등)을 별도로 가져와야 합니다. 이 버전 이전에는 모든 구성 요소가 일반적으로 단일 가져오기로 번들되었습니다.
  - **ES2020 컴파일:** SDK는 이 버전부터 ES2020 JavaScript 사양으로 컴파일됩니다. 빌드 환경 및 대상 브라우저가 ES2020 기능을 지원하는지 확인하십시오.
</Aside>

### 서비스 워커 설정

npm을 통해 SDK를 사용할 때, 서비스 워커 파일은 다음 위치에 있습니다:

```
node_modules/web-push-notifications/service-worker.js
```

**중요:** 빌드 또는 배포 프로세스 중에 이 서비스 워커 파일을 웹사이트의 루트로 복사해야 합니다. 이는 푸시 알림이 올바르게 작동하는 데 중요합니다.

예를 들어, webpack 프로젝트에서는 `copy-webpack-plugin`을 사용할 수 있습니다:

```javascript
const CopyWebpackPlugin = require('copy-webpack-plugin');

module.exports = {
  // ...other webpack config
  plugins: [
    new CopyWebpackPlugin({
      patterns: [
        {
          from: 'node_modules/web-push-notifications/service-worker.js',
          to: 'service-worker.js' // Copies to output directory root
        }
      ]
    })
  ]
};
```

Vite를 사용하는 경우, `vite-plugin-static-copy` 플러그인을 사용할 수 있습니다:


```javascript
// vite.config.js
import { defineConfig } from 'vite';
import { viteStaticCopy } from 'vite-plugin-static-copy'

export default defineConfig({
  // ...other vite config
  plugins: [
    // ...other plugins
    viteStaticCopy({
      targets: [
        {
          src: 'node_modules/web-push-notifications/service-worker.js',
          dest: '' // Copies to build output root
        }
      ]
    })
  ]
});
```
다른 빌드 시스템의 경우, 서비스 워커가 웹사이트 루트에서 사용 가능하도록 해당 파일 복사 메커니즘을 사용하십시오.

### 내장 위젯

Pushwoosh 웹 SDK는 사용자 상호 작용을 강화하고 구독 프로세스를 간소화하는 네 가지 내장 UI 위젯을 제공합니다. `PWSubscriptionPromptWidget`는 주로 Pushwoosh Control Panel 및 브라우저 설정을 통해 구성되지만, 다른 세 가지 위젯(`PWSubscriptionButtonWidget`, `PWSubscribePopupWidget`, `PWInboxWidget`)은 SDK의 `init` 메서드 내에서 직접 자세한 구성 옵션을 제공합니다.

각 위젯에 대한 개요는 다음과 같습니다:

1.  **구독 프롬프트 (`PWSubscriptionPromptWidget`)**
이 위젯은 사용자에게 푸시 알림 전송 권한을 요청하는 브라우저의 기본 프롬프트를 표시하는 역할을 합니다. 이 동작은 주로 브라우저 표준 및 Pushwoosh Control Panel에서 구성된 설정에 따라 제어됩니다. `pushwoosh.push(['init', {...}])` 호출 내에 특정 구성 매개변수가 없습니다.

2.  **구독 버튼 (`PWSubscriptionButtonWidget`)**
이 위젯은 사이트에 플로팅 버튼(종종 종 아이콘)을 추가하여 사용자가 알림 기본 설정을 쉽게 구독하거나 관리할 수 있도록 합니다.
*   **구성:** 이 위젯에 대한 설정은 `init` 호출의 `subscribeWidget` 객체 아래에서 관리됩니다.
*   **자세히 알아보기:** [푸시 구독 버튼](/ko/developer/pushwoosh-sdk/web-push-notifications/push-subscription-button/)

3.  **사용자 지정 구독 팝업 (`PWSubscribePopupWidget`)**
기본 브라우저 프롬프트를 표시하기 전에 알림 권한을 요청하는 보다 매력적인 방법을 제공하는 사용자 지정 가능한 팝업입니다.
*   **구성:** `init` 호출의 `subscribePopup` 객체를 사용하여 모양과 동작을 사용자 지정합니다.
*   **자세히 알아보기:** [사용자 지정 구독 팝업](/ko/developer/pushwoosh-sdk/web-push-notifications/custom-subscription-popup/)

4.  **인박스 위젯 (`PWInboxWidget`)**
이 위젯은 인앱 메시지 센터를 통합하여 사용자가 풍부한 푸시 알림 기록을 볼 수 있도록 합니다.
*   **구성:** `init` 호출의 `inboxWidget` 객체를 통해 관리됩니다.
*   **자세히 알아보기:** [웹 인박스 위젯](/ko/developer/pushwoosh-sdk/web-push-notifications/web-inbox-widget/)

아래 예시에 표시된 대로 이러한 위젯을 초기화하고 실행할 수 있습니다:

### 가져오기 및 초기화

```javascript title="Pushwoosh 가져오기 및 초기화"
import { Pushwoosh } from 'web-push-notifications';
import { PWSubscriptionPromptWidget } from 'web-push-notifications/widget-subscription-prompt';
import { PWSubscriptionButtonWidget } from 'web-push-notifications/widget-subscription-button';
import { PWSubscribePopupWidget } from 'web-push-notifications/widget-subscribe-popup';
import { PWInboxWidget } from 'web-push-notifications/widget-inbox';

const pushwoosh = new Pushwoosh();

pushwoosh.push(['init', {
  applicationCode: 'XXXXX-XXXXX', // Pushwoosh 애플리케이션 코드
  apiToken: 'XXXXXXX', // 장치 API 토큰
  defaultNotificationTitle: 'Pushwoosh',
  defaultNotificationImage: 'https://yoursite.com/img/logo-medium.png',
  serviceWorkerUrl: '/service-worker.js', // 복사된 서비스 워커 경로

  // 사용자 지정 구독 팝업 설정
  subscribePopup: {
    enable: true // 구독 팝업 활성화
    // 여기에 다른 옵션을 추가할 수 있습니다
  },

  // 푸시 구독 버튼 설정
  subscribeWidget: {
    enable: true // 구독 버튼 위젯 활성화
    // 여기에 다른 옵션을 추가할 수 있습니다
  },

  // 인박스 위젯 설정
  inboxWidget: {
    enable: true // 인박스 위젯 활성화
    // 여기에 다른 옵션을 추가할 수 있습니다
  }
}]);

pushwoosh.push(async () => {
  try {
    const widget = new PWSubscriptionPromptWidget(pushwoosh);
    await widget.run();
  } catch (error) {
    console.error('PWSubscriptionPromptWidget initialization failed:', error);
  }
});

pushwoosh.push(async () => {
  try {
    const widget = new PWSubscriptionButtonWidget(pushwoosh);
    await widget.run();
  } catch (error) {
    console.error('PWSubscriptionButtonWidget initialization failed:', error);
  }
});

pushwoosh.push(async () => {
  try {
    const widget = new PWSubscribePopupWidget(pushwoosh);
    await widget.run();
  } catch (error) {
    console.error('PWSubscribePopupWidget initialization failed:', error);
  }
});

pushwoosh.push(async () => {
  try {
    const widget = new PWInboxWidget(pushwoosh);
    await widget.run();
  } catch (error) {
    console.error('PWInboxWidget initialization failed:', error);
  }
});
```

## 링크

React 및 Vite를 사용한 예제 애플리케이션을 참조하십시오: https://github.com/Pushwoosh/websdk-npm-vite-react-example