I. 프로젝트 생성 및 초기 설정
| 단계 | 명령어 |
|---|
| 1. 프로젝트 생성 | npm create vite@latest 프로젝트이름 -- --template vue |
| 2. 디렉토리 이동 | cd 프로젝트이름 |
| 3. 종속성 설치 | npm install |
II. 필수 라이브러리 설치
FCM 기능과 PWA 구성을 위해 다음 두 가지 라이브러리를 설치합니다.
| 라이브러리 | 명령어 | 설명 |
|---|
| Firebase SDK | npm install firebase | FCM(Firebase Cloud Messaging)을 포함한 모든 Firebase 서비스를 사용할 수 있는 클라이언트 라이브러리를 설치합니다. |
| Vite PWA 플러그인 | npm install -D vite-plugin-pwa | Vite 환경에서 Service Worker와 Web App Manifest를 쉽게 구성하고 관리할 수 있도록 도와주는 개발 의존성 플러그인입니다. |
I. 프로젝트 설정 및 파일 구성
| 파일/폴더 | 역할 및 내용 |
|---|
vite.config.js | Vite PWA 플러그인 설정 및 FCM Service Worker 통합 (injectManifest 전략 사용). |
src/firebase.js | Vue 앱의 메인 스레드용 Firebase 초기화.환경 변수를 사용하여 보안 강화. |
src/App.vue | 알림 권한 요청, VAPID 키 사용 토큰 발급 및 Service Worker 등록 객체 전달 (FCM 필수). |
public/firebase-messaging-sw.js | 백그라운드 푸시 수신 처리를 담당하는 통합 Service Worker. Workbox 캐싱 활성화 및 FCM의 필수 Config 포함. |
public/pwa-*.png | PWA 설치 가능 요구사항을 충족하기 위한 필수 아이콘 파일. |
II. 코드
1. public/firebase-messaging-sw.js (가장 중요)
- 목적: 백그라운드 메시지 수신 및 Workbox 캐싱 활성화.
- 보안:
apiKey, authDomain 등 민감 정보는 제거하고, messagingSenderId 및 projectId 등 FCM 등록에 필수적인 최소 정보만 남깁니다.
importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.4.1/workbox-sw.js');
if (self.workbox) {
self.workbox.precaching.precacheAndRoute(self.__WB_MANIFEST || []);
}
importScripts('https://www.gstatic.com/firebasejs/9.1.0/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/9.1.0/firebase-messaging-compat.js');
const firebaseConfig = {
messagingSenderId: "본인 senderId",
};
const app = firebase.initializeApp(firebaseConfig);
const messaging = app.messaging();
messaging.onBackgroundMessage((payload) => {
console.log('[firebase-messaging-sw.js] Background Message received. ', payload);
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
icon: '/firebase-logo.png'
};
self.registration.showNotification(notificationTitle, notificationOptions);
});
2. vite.config.js
- 목적:
firebase-messaging-sw.js 파일을 주 Service Worker로 통합하여 등록 충돌 방지.
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { VitePWA } from 'vite-plugin-pwa'
export default defineConfig({
plugins: [
vue(),
VitePWA({
strategies: 'injectManifest',
srcDir: 'public',
filename: 'firebase-messaging-sw.js',
includeAssets: ['favicon.ico', 'apple-touch-icon.png', 'masked-icon.svg'],
manifest: {
name: 'My Vue PWA App',
short_name: 'Vue PWA',
theme_color: '#ffffff',
icons: [
{
src: 'pwa-192x192.png',
sizes: '192x192',
type: 'image/png',
purpose: 'maskable'
},
{
src: 'pwa-512x512.png',
sizes: '512x512',
type: 'image/png'
}
]
}
})
],
})
3. App.vue (<script setup>)
- 목적: 알림 권한 획득 및 FCM 토큰 발급.
- 토큰 발급 필수 요소:
vapidKey와 serviceWorkerRegistration 전달.
const requestPermissionAndGetToken = async () => {
try {
const permission = await Notification.requestPermission();
if (permission === 'granted') {
const registration = await navigator.serviceWorker.getRegistration('./firebase-messaging-sw.js');
const VAPID_KEY = import.meta.env.VITE_FIREBASE_VAPID_KEY;
currentToken.value = await getToken(messaging, {
vapidKey: VAPID_KEY,
serviceWorkerRegistration: registration
});
if (currentToken.value) {
console.log('FCM Registration Token:', currentToken.value);
}
}
} catch (err) {
console.error('An error occurred while retrieving token. ', err);
}
};
III. 실행 및 테스트 흐름 (누락 없음)
1. 빌드 및 배포 준비
| 순서 | 명령어 | 설명 |
|---|
| 1. | npm run build | 수정한 vite.config.js를 적용하여 PWA Service Worker를 통합한 최종 dist 폴더를 생성합니다. |
| 2. | npm install -g serve | 빌드된 파일을 실행하기 위해 정적 서버 도구 serve를 전역에 설치합니다. |
| 3. | serve -s dist | 빌드 결과물(dist)을 로컬 서버(http://localhost:3000)에 배포 및 실행합니다. |
2. FCM 최종 검증
| 순서 | 행동 | 확인 사항 |
|---|
| 1. | 브라우저 접속 후 토큰 복사 | 콘솔에 출력된 FCM Registration Token을 복사합니다. |
| 2. | Firebase 콘솔 접속 | Cloud Messaging 메뉴로 이동합니다. |
| 3. | 테스트 메시지 전송 | 복사한 토큰을 입력하고 알림을 전송합니다. |
| 4. | 알림 수신 확인 | 브라우저가 백그라운드(최소화) 상태일 때, 시스템 알림이 정상적으로 뜨는지 확인합니다. |
3. 다음 단계 (서버 연동 준비)
- 토큰 저장 로직 구현:
App.vue의 saveTokenToServer 주석 부분에 유저 ID와 함께 토큰을 Spring Boot 서버 API로 전송하는 HTTP 요청 코드를 구현합니다.