DEV Community

David Carr
David Carr

Posted on • Originally published at dcblog.dev on

Import SweetAlert2 into Laravel with NPM

Import SweetAlert2 into Laravel with NPM

SweetAlert2 is a great package for user-friendly alerts, normally I install by adding in script tags and then use the package as normal. This post will explain how to instead install with NPM in Laravel.

First, open your Laravel project in the terminal and add


npm install sweetalert2
Enter fullscreen mode Exit fullscreen mode

This will install the package into package.json that looks like:


"dependencies": {
    "sweetalert2": "^10.15.5"
}
Enter fullscreen mode Exit fullscreen mode

Next, we need to import SweetAlert2 into *resources/js/app.js *

Import to make the package available to the current file


import swal from 'sweetalert2';
Enter fullscreen mode Exit fullscreen mode

If you want to use SweetAlert2 globally you can add it to a window object:


window.Swal = swal;
Enter fullscreen mode Exit fullscreen mode

This can then be used directly in app.js or in any blade file.

Now we need to compile the changes into app.js by running:


npm run dev
Enter fullscreen mode Exit fullscreen mode

Using SweetAlert2 in a Blade file

To use in a blade file lets you need to ensure the content is loaded before attempting to use SweetAlert2 otherwise you will get an error. To do this we can add an event listener called DOMContentLoaded which will run only when the content is ready.


<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function () {
   //content goes here
});
</script>
Enter fullscreen mode Exit fullscreen mode

Here's an example of a confirmation alert:


<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function () {
   Swal.fire({
      title: 'Are you sure?',
      text: "You won't be able to revert this!",
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#3085d6',
      cancelButtonColor: '#d33',
      confirmButtonText: 'Yes, delete it!'
    }).then((result) => {
      if (result.isConfirmed) {
        Swal.fire(
          'Deleted!',
          'Your file has been deleted.',
          'success'
        )
      }
    })
});
</script>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)