# npm 使用指南

## 通过 npm 安装 Pushwoosh Web 推送 SDK

本指南将介绍如何在您的项目中使用 npm 安装和使用 Pushwoosh Web 推送通知 SDK。
本指南假设您对 npm 和 JavaScript 模块导入有基本的了解。

### 安装 SDK：

```bash title="安装 Pushwoosh Web 推送通知 SDK"
npm install web-push-notifications
```

<Aside type="caution" title="关于 SDK 版本的重要说明 (v3.45.0+)">
  从 **3.45.0** 版本开始，Pushwoosh Web SDK 引入了一种模块化方法来导入核心 SDK 及其 UI 小部件。

  - **单独导入：** 您现在需要单独导入主要的 `Pushwoosh` 类和任何所需的小部件（例如 `PWSubscriptionButtonWidget`、`PWSubscribePopupWidget` 等）。在此版本之前，所有组件通常都捆绑在一个导入中。
  - **ES2020 编译：** 从此版本开始，SDK 将编译为 ES2020 JavaScript 规范。请确保您的构建环境和目标浏览器支持 ES2020 功能。
</Aside>

### Service Worker 设置

当通过 npm 使用 SDK 时，Service Worker 文件位于：

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

**重要提示：** 在您的构建或部署过程中，您必须将此 Service Worker 文件复制到您网站的根目录。这对于推送通知正常工作至关重要。

例如，在 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
        }
      ]
    })
  ]
});
```
对于其他构建系统，请使用其各自的文件复制机制，以确保 Service Worker 在您网站的根目录可用。

### 内置小部件

Pushwoosh Web SDK 附带四个内置 UI 小部件，以增强用户交互并简化订阅过程。虽然 `PWSubscriptionPromptWidget` 主要通过 Pushwoosh 控制面板和浏览器设置进行配置，但其他三个小部件（`PWSubscriptionButtonWidget`、`PWSubscribePopupWidget` 和 `PWInboxWidget`）直接在 SDK 的 `init` 方法中提供详细的配置选项。

以下是每个小部件的概述：

1.  **订阅提示 (`PWSubscriptionPromptWidget`)**
此小部件负责显示浏览器的原生提示，以请求用户允许发送推送通知。其行为主要受浏览器标准和 Pushwoosh 控制面板中配置的设置的约束。它在 `pushwoosh.push(['init', {...}])` 调用中没有特定的配置参数。

2.  **订阅按钮 (`PWSubscriptionButtonWidget`)**
此小部件会在您的网站上添加一个浮动按钮（通常是铃铛图标），允许用户轻松订阅或管理其通知偏好设置。
*   **配置：** 此小部件的设置在 `init` 调用中的 `subscribeWidget` 对象下进行管理。
*   **了解更多：** [推送订阅按钮](/zh/developer/pushwoosh-sdk/web-push-notifications/push-subscription-button/)

3.  **自定义订阅弹窗 (`PWSubscribePopupWidget`)**
一个可自定义的弹窗，提供更具吸引力的方式来请求通知权限，然后再显示原生浏览器提示。
*   **配置：** 使用 `init` 调用中的 `subscribePopup` 对象自定义其外观和行为。
*   **了解更多：** [自定义订阅弹窗](/zh/developer/pushwoosh-sdk/web-push-notifications/custom-subscription-popup/)

4.  **收件箱小部件 (`PWInboxWidget`)**
此小部件集成了应用内消息中心，允许用户查看丰富的推送通知历史记录。
*   **配置：** 通过 `init` 调用中的 `inboxWidget` 对象进行管理。
*   **了解更多：** [Web 收件箱小部件](/zh/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', // your Pushwoosh Application Code
  apiToken: 'XXXXXXX', // Device API Token
  defaultNotificationTitle: 'Pushwoosh',
  defaultNotificationImage: 'https://yoursite.com/img/logo-medium.png',
  serviceWorkerUrl: '/service-worker.js', // path to your copied service worker

  // Custom Subscription Popup settings
  subscribePopup: {
    enable: true // Enable the subscription popup
    // other options can be added here
  },

  // Push subscription button settings
  subscribeWidget: {
    enable: true // Enable the subscription button widget
    // other options can be added here
  },

  // Inbox widget settings
  inboxWidget: {
    enable: true // Enable the inbox widget
    // other options can be added here
  }
}]);

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