I have a Rails 7 App that I'm using Importmap with. I'm loading the Bootstrap JS via the gem and docs so my config/importmap.rb has:
pin "popper", to: 'popper.js', preload: true
pin "bootstrap", to: 'bootstrap.min.js', preload: true
config/initializers/assets.rb
Rails.application.config.assets.precompile = %w( bootstrap.min.js popper.js )
application.js
import 'popper'
import * as bootstrap from 'bootstrap'
document.addEventListener("turbo:load", function() {
new bootstrap.Popover(document.getElementById('example'))
})
Stuff like dropdowns activated via data attributes work well but my custom JS gives the error: Uncaught TypeError: bootstrap.Popover is not a constructor
CodePudding user response:
How to initialize Popper (tooltips) with importmaps
You're very close. I changed your import statement for bootstrap in application.js
, and modified the pin
statements in importmaps to align with the documentation (linked below). Everything is working.
app/javascripts/application.js
// app/javascripts/application.js
import "@popperjs/core";
import "bootstrap";
document.addEventListener("turbo:load", function () {
// This code is copied from Bootstrap's docs. See link below.
var tooltipTriggerList = [].slice.call(
document.querySelectorAll('[data-bs-toggle="tooltip"]')
);
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
return new bootstrap.Tooltip(tooltipTriggerEl);
});
});
Note, the inner code is from Bootstrap's docs and will initialize all the tooltips on the screen.
config/importmap.rb
pin "application", preload: true
pin "@hotwired/turbo-rails", to: "turbo.min.js", preload: true
pin "@hotwired/stimulus", to: "stimulus.min.js", preload: true
pin "@hotwired/stimulus-loading", to: "stimulus-loading.js", preload: true
pin_all_from "app/javascript/controllers", under: "controllers"
# Note: Everything above was added by default. Added these two lines:
pin "bootstrap", to: "bootstrap.min.js", preload: true
pin "@popperjs/core", to: "popper.js", preload: true
The last two lines are slightly different than what you had, but are copy-pasted from the gem's docs.
As you did, I also had to add the following:
config/initializers/assets.rb
# ... default code above ...
Rails.application.config.assets.precompile = %w( bootstrap.min.js popper.js )