sweetalert2-bootstrap-4 は、Bootstrap 4/5 のデザイン言語に完全対応したモーダル通知ライブラリです。原作の sweetalert2 をベースに、CSS クラスとテーマを Bootstrap のコンポーネント仕様に再構築しており、JavaScript による簡潔な呼び出しで、一貫性のある UI 体験を実現します。
導入のメリット
- ネイティブなブートストラップ統合:ボタン、アイコン、色調、シャドウが Bootstrap の
.btn-primaryや.alert-successと自動的に連動 - ゼロコンフィグのレスポンシブ対応:画面幅に応じてモーダルサイズ・フォントサイズ・余白が自動調整
- Promise ベースの非同期フロー:コールバック関数ではなく
then()/catch()で処理を記述可能 - 軽量設計(~12KB gzipped):外部依存なし、CDN 経由でも即時利用可能
インストールと初期設定
npm 経由でのインストールが推奨されます:
npm install sweetalert2 bootstrap
HTML への読み込み例(Bootstrap 5 + ES Module 対応):
<!-- Bootstrap CSS -->
<link href="node_modules/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- SweetAlert2 Bootstrap テーマ -->
<link href="node_modules/sweetalert2-bootstrap-4/dist/sweetalert2-bootstrap-4.css" rel="stylesheet">
<!-- SweetAlert2 コア -->
<script src="node_modules/sweetalert2/dist/sweetalert2.all.min.js"></script>
基本的な使用例
成功通知の表示:
Swal.fire({
icon: 'success',
title: '保存完了',
text: '設定がサーバーに反映されました',
confirmButtonText: '了解',
customClass: {
confirmButton: 'btn btn-success'
}
});
確認ダイアログ(削除操作前):
Swal.fire({
title: '本当に削除しますか?',
text: 'この操作は元に戻せません。',
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#dc3545',
cancelButtonColor: '#6c757d',
confirmButtonText: '削除する',
cancelButtonText: 'キャンセル'
}).then((result) => {
if (result.isConfirmed) {
performDeletion(); // 削除処理関数
}
});
高度なカスタマイズ手法
動的テーマ切り替え(ダークモード対応):
const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
Swal.fire({
...defaultConfig,
customClass: {
popup: isDarkMode ? 'bg-dark text-light' : '',
confirmButton: isDarkMode ? 'btn-outline-light' : 'btn-primary'
}
});
HTML 内容の埋め込み(複雑な入力フォーム):
Swal.fire({
title: 'ユーザー情報編集',
html: `
<div class="mb-3">
<label class="form-label">氏名</label>
<input id="swal-input1" class="form-control" placeholder="例:山田 太郎">
</div>
<div class="mb-3">
<label class="form-label">メールアドレス</label>
<input id="swal-input2" class="form-control" type="email" placeholder="example@domain.com">
</div>
`,
focusConfirm: false,
preConfirm: () => {
const name = document.getElementById('swal-input1').value;
const email = document.getElementById('swal-input2').value;
if (!name || !email) {
Swal.showValidationMessage('すべての項目を入力してください');
}
return { name, email };
}
}).then(({ value }) => {
if (value) {
updateProfile(value);
}
});
トラブルシューティング
- モーダルが表示されない:Bootstrap の JavaScript(
popper.js,bootstrap.bundle.min.js)が正しく読み込まれているか確認 - スタイルが崩れる:
sweetalert2-bootstrap-4.cssがbootstrap.cssより後に読み込まれているか確認 - z-index 衝突:
Swal.fire({ ... })にheightAuto: falseとcustomClass: { popup: 'position-relative' }を追加してレイアウト制御
拡張機能の活用
以下のオプションでさらに柔軟な挙動を実現できます:
timer: 3000— 自動クローズ(3秒後)allowOutsideClick: false— 背景クリック無効化input: 'email'— 入力タイプを指定(text,password,selectなど)didOpen: () => { /* DOM 操作 */ }— 表示直後のカスタム処理