代码之家  ›  专栏  ›  技术社区  ›  Volkan

刺激中的Rails 7和Bootstrap错误-无法解析模块说明符Bootstrap

  •  1
  • Volkan  · 技术社区  · 2 年前

    我正在学习本教程: https://www.hotrails.dev/articles/rails-modals-with-hotwireEverything 运行良好,直到我创建了这个刺激控制器文件:

    import { Controller } from "@hotwired/stimulus"
    import * as bootstrap from "bootstrap"
    
    export default class extends Controller {
      connect() {
        this.modal = new bootstrap.Modal(this.element)
      }
    
      open() {
        if (!this.modal.isOpened) {
          this.modal.show()
        }
      }
    
      close(event) {
        if (event.detail.success) {
          this.modal.hide()
        }
      }
    }
    

    我收到以下错误:

    未能注册控制器:modal(controllers/modal_controller)TypeError:未能解析模块说明符“bootstrap”。相对引用必须以“/”开头/“,或”/“。”

    更多信息: 我在gemfile中有一个bootstrap gem,bootstrap CSS类是可访问和可用的。但是bootstrap js不可用,我不知道如何将它提供给我的Rails 7应用程序。

    此外,我在某个地方看到,我必须通过添加引导程序的最后两行来更新application.js文件,我想与您核实一下是否正确:

    import "@hotwired/turbo-rails"
    import "controllers" 
    import * as bootstrap from "bootstrap" 
    window.bootstrap = bootstrap;
    

    如何使Bootstrap JS也可以在我的Rails 7应用程序中使用?

    非常感谢。

    更新:

    我还做了以下工作:

    npm install bootstrap
    

    我更新了 app/javascript/application.js 文件:

    import "@hotwired/turbo-rails"
    import "controllers"
    import "bootstrap"
    
    import * as bootstrap from "bootstrap"
    
    window.bootstrap = 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"
    
    pin "bootstrap", to: "bootstrap/dist/js/bootstrap.bundle.min.js", preload: true
    

    但我仍然没有将Bootstrap JS加载到我的应用程序中,并且我仍然在控制台中收到相同的错误: 项:1未捕获的类型错误:未能解析模块说明符“bootstrap”。相对引用必须以“/”、“./”或“../”开头。

    1 回复  |  直到 2 年前
        1
  •  1
  •   Alex    2 年前

    Rails默认使用导入映射,但不使用 节点模块 要查找包:

    # config/importmap.rb
    
    pin "bootstrap", to: "https://ga.jspm.io/npm:[email protected]/dist/js/bootstrap.esm.js"
    pin "@popperjs/core", to: "https://ga.jspm.io/npm:@popperjs/[email protected]/lib/index.js"
    

    或者只使用 importmap 命令:

    $ bin/importmap pin bootstrap
    
    import * as bootstrap from "bootstrap"
    
    // or just get what you need
    import { Modal } from "bootstrap"
    

    https://github.com/rails/importmap-rails