How to install Bootstrap and jQuery in Rails
--The old method using Gem --Method using Webpacker from 6.0
There are two, but this time we will adopt the * latter *.
--Those who want to use bootstrap and jQuery with Rails6.0
$ rails -v
Rails 6.0.3.1
$ ruby -v
ruby 2.7.0p0 (2019-12-25 revision 647ee6f091) [x86_64-darwin19]
$ yarn install jquery popper.js bootstrap
In Rails, Bootstrap depends on packages called jQuery and popper.js, so install them together. Also, packages are installed under the ** node_modules directory **.
config/webpack/environment.js
const { environment } = require('@rails/webpacker')
const webpack = require('webpack')
environment.plugins.prepend('Provide',
new webpack.ProvidePlugin({
$: 'jquery/src/jquery',
jQuery: 'jquery/src/jquery',
Popper: ['popper.js', 'default']
})
)
module.exports = environment
It is set to load jQuery and popper in advance. By doing this, you don't have to bother to read with ** require or @import **.
app/javascripts/packs/application.js
require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
require('bootstrap/dist/js/bootstrap.min.js')
app/assets/stylesheets/application.scss
*= require bootstrap/dist/css/bootstrap.min.css
*= require_tree .
*= require_self
Bootstrap should be loaded before ** self-written css (* = require_self) **.
app/javascript/packs/application.js
require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
require("jquery")
require('bootstrap/dist/js/bootstrap.min.js')
Usage
new.html.erb
<div>
//abridgement
<%= javascript_pack_tag 'users/new' %>
</div>
Make the js file available by calling the users / new.js file under the javascript / packs directory.
Recommended Posts