SweetAlert2 전역 설정으로 프로젝트 전역에 동일한 스타일과 옵션으로 팝업 UI를 일관성 있게 유지할 수 있습니다. Global Defaults 기능을 활용하면 매번 옵션을 작성할 필요 없이 재사용 팝업을 손쉽게 만들 수 있습니다. 이번 글에서는 전역 설정 방법과 재사용 팝업 제작, 그리고 고급 활용 예제를 함께 살펴봅니다.
전역 설정(Global Defaults) 개념
SweetAlert2의 Swal.mixin()
또는 Swal.setDefaults()
를 사용하면 모든 팝업에 공통적으로 적용되는 설정을 지정할 수 있습니다.
이 방식은 디자인, 버튼 색상, 아이콘 스타일 등을 한 번에 통일할 때 유용합니다.
전역 설정 예제 – Swal.mixin()
사용
<!-- SweetAlert2 CDN -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
// 공통 팝업 설정
const swalDefault = Swal.mixin({
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: '확인',
cancelButtonText: '취소',
showCancelButton: true,
background: '#f9f9f9',
customClass: {
popup: 'my-swal-popup'
}
});
// 팝업 호출
document.getElementById('btn1').addEventListener('click', () => {
swalDefault.fire({
title: '전역 설정 팝업',
text: '이 팝업은 공통 스타일을 사용합니다.',
icon: 'info'
});
});
</script>
<button id="btn1">팝업 열기</button>
HTML💡 TIP
Swal.mixin()
은 새로운 Swal 인스턴스를 반환하므로 변수에 담아 사용- CSS를
customClass
로 지정해 전체 디자인을 맞출 수 있음
전역 설정 예제 – Swal.setDefaults()
사용
// SweetAlert2 기본 옵션 설정
Swal.setDefaults({
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
showCancelButton: true,
confirmButtonText: '확인',
cancelButtonText: '취소'
});
// 팝업 호출
Swal.fire({
title: 'SetDefaults 사용',
text: '전역 기본값이 적용된 팝업입니다.',
icon: 'success'
});
JavaScript💡 TIP
setDefaults
는 Swal 자체의 기본 옵션을 변경- 프로젝트 전역에서 동일한 옵션을 쓸 때 가장 간단한 방법
재사용 팝업 함수 만들기
function showAlert(title, text, icon = 'info') {
Swal.fire({
title: title,
text: text,
icon: icon
});
}
// 호출 예시
showAlert('환영합니다!', '로그인이 완료되었습니다.', 'success');
showAlert('경고', '다시 시도해주세요.', 'error');
JavaScript💡 TIP
- 재사용 함수를 만들면 코드 반복 최소화 + 유지보수 편의성 향상
- API 호출 후 성공/실패 메시지 같은 패턴에 적합
실무 활용 팁
- 프로젝트 규모가 클수록 전역 설정 필수 – UI 일관성 유지
- CSS 클래스 활용 – 디자인 변경 시 코드 수정 없이 스타일 업데이트 가능
- i18n(다국어 지원) – 전역 설정에서 버튼 텍스트를 locale에 맞춰 변경
- 테마별 전역 설정 – mixin 여러 개를 만들어 다크모드/라이트모드 전환 가능
고급 예제 – 다크모드/라이트모드 테마 전역 설정
<style>
/* 공통 팝업 스타일 */
.my-popup {
border-radius: 16px;
font-size: 16px;
}
/* 다크모드 전용 */
.my-popup-dark {
background: #2c2c2c;
color: #fff;
}
/* 라이트모드 전용 */
.my-popup-light {
background: #ffffff;
color: #333;
}
</style>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
// 라이트모드 팝업
const swalLight = Swal.mixin({
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
showCancelButton: true,
customClass: {
popup: 'my-popup my-popup-light'
}
});
// 다크모드 팝업
const swalDark = Swal.mixin({
confirmButtonColor: '#4cafef',
cancelButtonColor: '#e57373',
showCancelButton: true,
customClass: {
popup: 'my-popup my-popup-dark'
}
});
// 모드 전환에 따라 팝업 호출
function showThemedAlert(mode, title, text, icon) {
const swalInstance = mode === 'dark' ? swalDark : swalLight;
swalInstance.fire({ title, text, icon });
}
// 예시
document.getElementById('btnLight').addEventListener('click', () => {
showThemedAlert('light', '라이트모드 팝업', '밝은 테마입니다.', 'info');
});
document.getElementById('btnDark').addEventListener('click', () => {
showThemedAlert('dark', '다크모드 팝업', '어두운 테마입니다.', 'info');
});
</script>
<button id="btnLight">라이트모드 팝업</button>
<button id="btnDark">다크모드 팝업</button>
HTML💡 TIP
customClass.popup
으로 모드별 스타일 완전 변경 가능- 버튼 색상, 배경, 글자 색 등 UI 전체를 테마에 맞춤
고급 예제 – API 응답별 자동 팝업 처리
// 전역 기본 설정
Swal.setDefaults({
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
showCancelButton: false
});
// API 응답 처리 팝업 함수
function handleApiResponse(response) {
const { status, message } = response;
if (status === 'success') {
Swal.fire({ title: '성공!', text: message, icon: 'success' });
} else if (status === 'warning') {
Swal.fire({ title: '경고', text: message, icon: 'warning' });
} else {
Swal.fire({ title: '실패', text: message, icon: 'error' });
}
}
// 예시 응답
handleApiResponse({ status: 'success', message: '데이터가 저장되었습니다.' });
handleApiResponse({ status: 'error', message: '저장 중 오류가 발생했습니다.' });
JavaScript💡 TIP
- SPA(React, Vue) 환경에서 API 응답에 따라 팝업 자동 호출 가능
- 응답 처리 로직과 UI 호출을 일원화해 유지보수 편리
마무리
SweetAlert2의 Global Defaults 기능을 사용하면 팝업 디자인과 옵션을 일관성 있게 유지할 수 있습니다.Swal.mixin()
은 특정 스타일 팝업 재사용에, Swal.setDefaults()
는 전체 팝업 기본값 지정에 적합합니다.
고급 예제처럼 테마별 설정과 API 응답 처리 팝업을 결합하면 실무 활용도가 극대화됩니다.