Как заставить Bootstrap Javascript работать в Ruby на Rails 6 - PullRequest
2 голосов
/ 29 февраля 2020

Во-первых, я понимаю, что этот вопрос задавался несколько раз раньше, однако все ответы, которые я видел, не сработали для меня.

Я добавил bootstrap в свое приложение Rails, используя bootstrap драгоценный камень, или, по крайней мере, я думаю, что у меня есть. css и стили для bootstrap все есть и работают, но функции javascript отсутствуют

Я довольно новичок в Rails, поэтому я, вероятно, пропустил что-то действительно очевидное, Прикрепленные файлы, я думаю, имеют отношение ниже.

У меня есть следующие файлы, любые предложения или помощь будут с благодарностью

gemfile

source 'https://rubygems.org'

ruby '2.7.0'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 6.0.2', '>= 6.0.2.1'
# Use sqlite3 as the database for Active Record
gem 'sqlite3', '~> 1.4'
# Use Puma as the app server
gem 'puma', '~> 4.1'
# Use SCSS for stylesheets
gem 'sass-rails', '>= 6'
# Transpile app-like JavaScript. Read more: https://github.com/rails/webpacker
gem 'webpacker', '~> 4.0'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.7'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 4.0'
# Use Active Model has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Active Storage variant
# gem 'image_processing', '~> 1.2'

# Reduces boot times through caching; required in config/boot.rb
gem 'bootsnap', '>= 1.4.2', require: false
# Use jquery as the JavaScript library
gem 'jquery-rails'
gem 'bootstrap', '~> 4.4', '>= 4.4.1'
gem 'devise'

group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
end

group :development do
# Access an interactive console on exception pages or by calling 'console' anywhere in the code.
gem 'web-console', '>= 3.3.0'
gem 'listen', '>= 3.0.5', '< 3.2'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
gem 'spring-watcher-listen', '~> 2.0.0'
end

group :test do
# Adds support for Capybara system testing and selenium driver
gem 'capybara', '>= 2.15'
gem 'selenium-webdriver'
# Easy installation and use of web drivers to run system tests with browsers
gem 'webdrivers'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

приложение / активы / таблицы стилей / приложения.s css

/*
* This is a manifest file that'll be compiled into application.css, which will include all the files
* listed below.
*
* Any CSS and SCSS file within this directory, lib/assets/stylesheets, or any plugin's
* vendor/assets/stylesheets directory can be referenced here using a relative path.
*
* You're free to add application-wide styles to this file and they'll appear at the bottom of the
* compiled file so the styles you add here take precedence over styles defined in any other CSS/SCSS
* files in this directory. Styles in this file should be added after the last require_* statement.
* It is generally better to create a new file per style scope.
*
*/
@import "bootstrap";
body {
    padding-top: 70px;
  }

приложение / активы / javascripts / application. js

// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require bootstrap
//= require_tree .

1 Ответ

3 голосов
/ 29 февраля 2020

Поскольку Rails 6 следует за webpacker, вам не нужно устанавливать гем, сделайте это вместо этого

В вашем домашнем каталоге Rails выполните эту команду, чтобы установить jQuery, popper.js и bootstrap, jquery и popper. js являются зависимостями bootstrap.

yarn add bootstrap@4.4.1 jquery popper.js

Затем добавьте это в ваш config / webpack / environment. js

const { environment } = require('@rails/webpacker') // already present

const webpack = require('webpack')
environment.plugins.append('Provide', new webpack.ProvidePlugin({
  $: 'jquery',
  jQuery: 'jquery',
  Popper: ['popper.js', 'default']
}))

module.exports = environment // already present

Затем создайте папку с именем src внутри app/javascript/packs, а затем создайте файл application.scss внутри вновь созданной папки src

Добавьте эту строку во вновь созданный application.scss файл

@import '~bootstrap/scss/bootstrap';

И, наконец, в файле app/javascript/packs/application.js, добавьте

import 'bootstrap'
import './src/application.scss'

Перезагрузите сервер, Bootstrap установлен и должен работать!

Подробнее о Webpacker - https://prathamesh.tech/2019/08/26/understanding-webpacker-in-rails-6/

Надеюсь, это поможет!

...