ruby-on-rails - 我正在尝试通过在 Rails 中使用 webpacker 来安装 toastr
问题描述
我正在尝试通过在 Rails 中使用 webpacker 来安装 toastr
现在,我正在使用 toastr bygem 'toastr-rails'
但是使用替换它yarn add toastr
我如何设置app/javascript/packs/application.js
?
这是我的应用程序中的 application.js
app/japascript/packs/application.js
import "jquery"
global.$ = require("jquery")
// JS-----
// install by yarn
import 'modaal/dist/js/modaal'
import 'flatpickr/dist/flatpickr'
require("jquery-ui-bundle")
// CSS ------
// install by yarn
import 'flatpickr/dist/flatpickr.min.css';
import 'font-awesome/css/font-awesome.min.css';
import 'jquery/dist/jquery';
import 'stylesheets/application';
import 'javascripts/application';
require.context('../images', true, /\.(png|jpg|jpeg|svg)$/);
$("#login-button").click(function(event){
event.preventDefault();
$('form').fadeOut(500);
$('.wrapper').addClass('form-success');
});
console.log('Hello World from Webpacker')
// Support component names relative to this directory:
var componentRequireContext = require.context("components", true)
var ReactRailsUJS = require("react_ujs")
ReactRailsUJS.useContext(componentRequireContext)
config/initializers/asset.rb 我必须在asset.rb中添加一些东西吗?
# Be sure to restart your server when you modify this file.
# Version of your assets, change this if you want to expire all your
assets.
Rails.application.config.assets.version = '1.0'
# Add additional assets to the asset load path.
# Rails.application.config.assets.paths << Emoji.images_path
# Add Yarn node_modules folder to the asset load path.
Rails.application.config.assets.paths <<
Rails.root.join('node_modules')
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in the app/assets
# folder are already added.
# Rails.application.config.assets.precompile += %w( admin.js admin.css
)
解决方案
在带有 webpacker 的 rails 应用程序中使用 toastr:
- 用纱线安装烤面包机:
yarn add toastr
- 在你的 application.js 中加载 lib:
import toastr from 'toastr';
toastr.options = {
"closeButton": true
.... add options here ...
};
global.toastr = toastr;
- 创建辅助方法(例如在您的 application_helper.rb 文件中):
def custom_bootstrap_flash
flash_messages = []
flash.each do |type, message|
type = 'success' if type == 'notice'
type = 'error' if type == 'alert'
text = "toastr.#{type}('#{message}');"
flash_messages << text.html_safe if message
end
flash_messages = flash_messages.join('\n')
"<script>$(document).ready(function() { #{ flash_messages } });</script>".html_safe
end
- 在布局文件(app/views/layouts/application.html.erb)的底部使用它:
<%= custom_bootstrap_flash %>
推荐阅读
- laravel - Nuxt Auth + Laravel Passport - 本地方案与护照提供者
- python - pygame按住lkey延迟
- javascript - 关于处理来自 DOM 事件的错误的问题
- r - “survival”包中的 survfit 函数出错:“strata(mf[ll]) 中的错误:所有参数的长度必须相同”
- python - 在多个数据帧中按相同序列查找行
- react-native - 带有 M1 芯片的 Mac 上的 react-native-plaid-link-sdk
- python - ModuleNotFoundError:没有名为“应用程序”的模块 [将 Django 部署到 AWS]
- reactjs - 反应 i18 在循环内翻译动态值
- python - Selenium 定位不可点击的元素
- python - Django:“[Errno 13] Permission denied: '/samples'” 在通过模型上传文件期间