简体   繁体   English

Sweet Alert 2 在 Rails 7 应用程序中无法正常工作

[英]Sweet Alert 2 is not working properly in Rails 7 Application

I attempted to integrate the Sweet Alert 2 java-script library for customising standard alert boxes into a Rails 7 application, but I received the following error message: "Swal is not defined."我试图将用于自定义标准警报框的Sweet Alert 2 java 脚本库集成到 Rails 7 应用程序中,但收到以下错误消息:“Swal 未定义。” I'm using Ruby 3 and Rails 7.我正在使用 Ruby 3 和 Rails 7。

I initially attempted to use the " sweet-alert2-rails " gem in my Rails application, but there are no current updates available.我最初尝试在我的 Rails 应用程序中使用“ sweet-alert2-rails ”gem,但目前没有可用的更新。 I therefore attempted to accomplish this using import map, and I did so by running the following line.因此,我尝试使用 import map 来完成此操作,并且我通过运行以下行来完成此操作。

bin/importmap pin sweetalert2

On top of that, I added the lines below to the application.js最重要的是,我将下面的行添加到application.js

import Swal from "sweetalert2"

I encountered the aforementioned problem when attempting to use "Sweet Alert 2" in my view files .我在我的视图文件中尝试使用“Sweet Alert 2”时遇到了上述问题。

Swal.fire(
  'Good job!',
  'You clicked the button!',
  'success'
)

To integrate Sweet Alerts into my Rails application, I used these links.为了将 Sweet Alerts 集成到我的 Rails 应用程序中,我使用了这些链接。

https://sweetalert2.github.io/ https://sweetalert2.github.io/

https://github.com/sweetalert2/sweetalert2 https://github.com/sweetalert2/sweetalert2

You defined Swal in application.js using import Swal from "sweetalert2" , and then you are trying to use it in your view files, so it is saying that Swal is not defined.您使用import Swal from "sweetalert2"在 application.js 中定义了Swal ,然后您试图在您的视图文件中使用它,所以它说 Swal 未定义。

Previously, in rails 6, we added " sweet alert " using "yarn install," and the same error occurred.之前,在rails 6中,我们使用“yarn install”添加了“ sweet alert ”,也出现了同样的错误。 Hence, to solve this error either in Rails 6 or in Rails 7, you need to add the following line inside your application.js .因此,要在 Rails 6 或 Rails 7 中解决此错误,您需要在application.js中添加以下行。

import Swal from 'sweetalert2';
window.Swal = Swal;

Adding window.Swal will undoubtedly fix your problem in Rails 7.添加window.Swal无疑会解决您在 Rails 7 中的问题。


You can find references on my blog and in my GitHub repository.您可以在我的博客和我的 GitHub 存储库中找到参考资料。 I have written this article for Rails 7.0.4 and Ruby 3.1.0.我为 Rails 7.0.4 和 Ruby 3.1.0 写了这篇文章。 and also implemented the code for the same version.并且还实现了相同版本的代码。

Blog: https://rutikkpatel.medium.com/sweet-alert-2-in-ruby-on-rails-7-3f4cffe1ea5f博客: https://rutikkpatel.medium.com/sweet-alert-2-in-ruby-on-rails-7-3f4cffe1ea5f

GitHub Repository: https://github.com/rutikkpatel/Sweet-Alert-Rails GitHub 存储库: https://github.com/rutikkpatel/Sweet-Alert-Rails

I hope that will help you with your issue.我希望这会帮助你解决你的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM