Search code examples
javascriptvuejs2sweetalert2

Vue.use(plugin) causing error: Vue is a constructor and should be called with the `new` keywor


Plugin involved - https://www.npmjs.com/package/sweetalert

Code in main.js

import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap-vue/dist/bootstrap-vue.css';
import BootstrapVue from 'bootstrap-vue';

import Vue from 'vue';
import Vuetify from 'vuetify';
import swal from 'sweetalert';
import App from './App';
import router from './router';

Vue.use(BootstrapVue);
Vue.use(Vuetify);
Vue.use(swal);

Error received in browser:

Uncaught SweetAlert: 1st argument ('function Vue (options) {
if ("development" !== 'production' &&
!(this instanceof Vue)
) {
warn('Vue is a constructor and should be called with the new
keyword');
}
this._init(options);
}') is invalid


Solution

  • As mentioned in the comments, the sweetalert module (from https://www.npmjs.com/package/sweetalert) is not a Vue plugin so you cannot use it in...

    Vue.use(swal)
    

    What you can do is create a plugin. For example, this will add the swal() function to Vue as a global method (Vue.swal()) and an instance method (this.$swal())

    import Vue from 'vue'
    import swal from 'sweetalert'
    
    Vue.use({
      // this is the required "install" method for Vue plugins
      install (Vue) {
        Vue.swal = swal
        Vue.prototype.$swal = swal
      }
    })
    

    I highly recommend using an existing Vue plugin like vue-sweetalert2 though.