Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

nhayder's avatar
Level 13

sweetalert2 returning Uncaught ReferenceError: swal is not defined with vue

just installed sweetalert2 as my primary alert system, as per the docs https://sweetalert2.github.io/#download i have npm installed it and added these for configuration on my main app.js file

require('./bootstrap');

window.Vue = require('vue');

import VModal from 'vue-js-modal'
const swal = require('sweetalert2') // added here

Vue.use(VModal)

also i created a function to show alerts like this

        alertSuccess : function(msg){

            const toast = swal.mixin({
              toast: true,
              position: 'bottom-start',
              showConfirmButton: false,
              timer: 3000,
            });

            toast({
              type: 'success',
              title: msg,
            })

        },

unfortunately, chrome is showing this error on devTools

Uncaught ReferenceError: swal is not defined

What seems to be the problem ?

0 likes
3 replies
D9705996's avatar
D9705996
Best Answer
Level 51

You are trying to use the swal variable outside the scope of where it is defined and isn't available in the global scope.

Change

const swal = require('sweetalert2') // added here

to 

window.swal = require('sweetalert2') // added here

The rest of you code should then work

1 like
D9705996's avatar

You might consider using https://github.com/avil13/vue-sweetalert2#readme

You can the do something like


import Vue from 'vue';
import VueSweetalert2 from 'vue-sweetalert2';
 
Vue.use(VueSweetalert2);

...

alertSuccess : function(msg){
  this.$swal(({
    toast: true,
    position: 'bottom-start',
    showConfirmButton: false,
    timer: 3000,
    type: 'success',
    title: msg,
  });       
}
1 like
nhayder's avatar
Level 13

@D9705996 this work, and the error removed

window.swal = require('sweetalert2') // added here

1 like

Please or to participate in this conversation.