Uncaught TypeError: Class constructor SweetAlert cannot be invoked without 'new'

Hi,

After updating meteor version, I can not use the sweetalert2 npm package.

import swal from 'sweetalert2';
import { TAPi18n } from 'meteor/tap:i18n';

export default class SwalHelper {

  static message(title, type = 'success', options = {}) {
    return swal({
      type: type,
      title: title,
      showCloseButton: true,
      confirmButtonText: TAPi18n.__('global.close'),
      confirmButtonClass: 'btn btn-primary',
      buttonsStyling: false,
      ...options
    });
  }

How can I fix?

Thanks

Have you tried the fix suggested in the error message and created a SweetAlert instance with new?

Looking at their github, it could be that after a Meteor update that the bundler is now using module instead of main?

This is their package.json:

  "main": "dist/sweetalert2.all.js",
  "browser": "dist/sweetalert2.all.js",
  "module": "src/sweetalert2.js",

And src/sweetalert2.js exports the class itself. I’m assuming the dist version exports an instance so you don’t need to new it first

1 Like

Yes, I added new between return and swal and it works now but it’s weird.

  static toast(title, icon = 'success', options = {}) {
    return new swal({
      toast: true,
      position: 'top-end',
      showConfirmButton: false,
      timer: 6000,
      icon: icon,
      title: title,
      showCloseButton: true,
      ...options
    });
  }

Yeah I would suggest creating an instance at the start of the file and using it like you would have in the past. Not sure how much work they do during construction:

import SweetAlert2 from 'sweetalert2';
import { TAPi18n } from 'meteor/tap:i18n';

const swal = new SweetAlert2();

export default class SwalHelper {

  static message(title, type = 'success', options = {}) {
    return swal({

It’s really bad that they don’t mention this anywhere in their documentation, so you need to look at their code to work it out

1 Like