[Ruby] [Webpacker] Summary of how to install Bootstrap and jQuery in Rails 6.0

1 minute read

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 *.

Reference target person

–Those who want to use bootstrap and jQuery with Rails6.0

environment

$ rails -v
Rails 6.0.3.1
$ ruby -v
ruby 2.7.0p0 (2019-12-25 revision 647ee6f091) [x86_64-darwin19]

Manage packages with Webpaker

$ 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 **.

Introducing bootstrap

Webpack settings

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 **.

Load javascript made by bootstrap

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')

Load bootstrap CSS

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) **.

Introduction of jQuery

load jQuery

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

Load your own JavaScript file

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.