Bootstrap JS 不适用于 Rails Importmap

Bootstrap JS not working with Rails Importmap

提问人:Mark Robinson 提问时间:12/14/2022 最后编辑:Mark Robinson 更新时间:12/17/2022 访问量:1040

问:

我有一个 Rails 7 应用程序,我正在使用 Importmap。我正在通过 gem文档加载 Bootstrap JS,所以我的 config/importmap.rb 有:

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 )

应用程序.js

import 'popper'
import * as bootstrap from 'bootstrap'
document.addEventListener("turbo:load", function() {
  new bootstrap.Popover(document.getElementById('example'))
})

通过数据属性激活的下拉列表之类的东西效果很好,但我的自定义 JS 给出了错误:Uncaught TypeError: bootstrap.Popover is not a constructor

javascript ruby-on-rails twitter-bootstrap 导入映射

评论


答:

6赞 Matt 12/17/2022 #1

如何初始化 Popper(工具提示)importmaps

你离得很近。我更改了 bootstrap 的 import 语句,并修改了 importmaps 中的语句以与文档保持一致(链接如下)。一切都在工作。application.jspin

应用程序/JavaScripts/应用程序.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);
  });
});

请注意,内部代码来自 Bootstrap 的文档,将初始化屏幕上的所有工具提示。

配置/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

最后两行与您的内容有不同,但是从 gem 的文档中复制粘贴而来

正如你所做的那样,我还必须添加以下内容:

config/initializers/assets.rb

# ... default code above ...
Rails.application.config.assets.precompile += %w( bootstrap.min.js popper.js )