See also: https://blog.robsdomain.com/twitter-bootstrap-in-rails-6/
Rails 6 mades large changes to how asset compilation is done. In specific sprockets
has been removed for javascript processing and replaced with the common webpack
utility. Sprockets remains in usage for CSS processing.
When it comes to asset bundling, the "Rails way" is webpack for JavaScript and Sprockets for everything else. The default setup in a fresh Rail 6 install, similar to what Basecamp uses, still compiles CSS, images, and fonts with Sprockets.
This means, if you're a member of the Basecamp camp, all your webpack JavaScript source files would live in app/javascript and all your Sprockets CSS and images would remain in app/assets. Running rails assets:precompile will first build all the Sprockets assets into the public/assets directory, then will build all the webpack assets into the public/packs directory.
Why Does Rails 6 include Sprockets
- Install Bootstrap via
yarn
yarn add [email protected] jquery popper.js
- Update
config/webpack/environment.js
const { environment } = require('@rails/webpacker')
const webpack = require('webpack')
environment.plugins.append('Provide', new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
Popper: ['popper.js', 'default']
}))
module.exports = environment
- Update
app/javascript/packs/application.js
// Other impots
import 'bootstrap'
4a. Co-locating CSS and JavaScript:
Add a stylesheets
folder with application.scss
to your javascript/packs
# app/javascript/packs/stylesheets/application.scss
@import "~bootstrap/scss/bootstrap"; // never forget the semicolon at the end
@import "./_custom";
# app/javascript/packs/stylesheets/_custom.scss
h1 {
color: red;
}
4b. Including Asset Pipeline in Webpack This avenue lets you keep your CSS, images and styling separate from your javascript.
Update the config/webpack.yml
to include the app/assets
directory in resolved_paths
resolved_paths: ['app/assets']
You will then need to manually import your style sheets into your app/javascript/packs/stylesheets/application.scss
// app/assets/stylesheets/home.css
h1 { color: green; }
// app/javascript/stylesheets/application.scss
@import "~bootstrap/scss/bootstrap"; // never forget the semicolon
@import "./_custom";
@import "stylesheets/home";
- Add to
app/assets/stylesheets/application.css
:
// if .scss
@import "bootstrap/scss/bootstrap";
// or if .css
*= require bootstrap/scss/bootstrap
(optional) 5. You can use the <%= javascript_pack_tag 'your_pack_componenent.js' %>
to import specific JavaScript bundles into the pages
https://github.com/rails/webpacker/blob/master/README.md https://medium.com/@adrian_teh/ruby-on-rails-6-with-webpacker-and-bootstrap-step-by-step-guide-41b52ef4081f https://www.timdisab.com/installing-bootstrap-4-on-rails-6/
You are a live saver! Thank you @robertsimoes 😄