首页 > 解决方案 > 我正在尝试通过在 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     
)

标签: ruby-on-railswebpack

解决方案


在带有 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 %>

推荐阅读