Bootstrap 5.1 not working in JSBundling Rails 7?

Viewed 1095

I started using the default Rails template, and now I want to use Bootstrap v5.1 with Rails. I've removed Importmap-Rails and proceeded with adding JSBundling-Rails and CSSBundling-Rails. The styling works properly, but none of the Bootstrap JavaScript commands seem to be working. What am I doing wrong?

2 Answers

When migrating from Importmap to JSBundling + CSSBundling, make sure that you remove the remnant files. Delete config/importmap.rb and bin/importmap.

There will also be some remnants containing hotwire turbo and hotwire stimulus. If you're not planning to use them, delete app/javascript/controllers and clear the lines inside of app/javascript/application.js. If incase, you want the hotwire libraries, first add jsbundling-rails and cssbundling-rails to the Gemfile. Complete their setup first using rails javascript:install:[esbuild|rollup|webpack] and rails css:install:bootstrap

There might be some conflict in bin/dev, but I haven't noticed anything different. So you can either discard, or keep the conflicted version of the file.

Most of the required files will be auto-generated, and lines auto-appended in pre-existing files, but if Bootstrap v5.1 still isn't working in rails, with JSBundling and CSSBundling:

  • Make sure that:

    import * as bootstrap from "bootstrap"
    

    has been added to the app/javascript/application.js file.

  • See if app/assets/stylesheets has application.bootstrap.scss instead of application.css, and the content inside is:

    @import 'bootstrap/scss/bootstrap';
    @import 'bootstrap-icons/font/bootstrap-icons';
    
  • In the app/assets/config/manifest.js file, make sure that the builds directory is included:

    //= link_tree ../images
    //= link_tree ../../javascript .js
    //= link_tree ../../../vendor/javascript .js
    
    // => add the line below, with the double slashes.
    //= link_tree ../builds
    
  • Do not forget to run the rails assets:precompile command. It would be better to close the server first, and then run this command.

I had some major problems getting bootstrap 5.1.3 javascripts working in rails 7.0.2.4. Tooltips and dropdowns were intermittent.

Firstly always use bin/dev to start the rails server in development (rather than the rails server command).

What I had to do to get javascript functionality back into my rails 7 app was go into app/javascript/application.js and change this

import "@hotwired/turbo-rails"

to this

import { Turbo } from "@hotwired/turbo-rails"
Turbo.session.drive = false

and everything began to work as expected!

References


Things you may also try

  • Each time before starting the server, use these commands to clear everything:
rake assets:clean
rake assets:clobber
rake tmp:clear
  • Hard refresh (ctrl + click on refresh) on every page load, or command + shift + r
Related