我遵循这个教程: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()
    }
  }
}

我收到以下错误:

"Failed to register controller: modal (controllers/modal_controller) TypeError: Failed to resolve module specifier "bootstrap". Relative references must start with either "/", "./", or "../"."

更多信息: 我有一个gem bootstrap 在gem文件中, bootstrap css类是可访问和可用的.但Bootstrap js不可用,我不知道如何将其用于我的rails 7应用程序.

此外,我还在某个地方看到,我必须通过添加用于 bootstrap 的最后两行来更新Applation.js文件,我想请您判断一下它是否正确:

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

如何让Bootstrap JS在我的Rails7应用程序中也可用?

谢谢

最新情况:

我还做了以下工作:

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加载到我的应用程序中,并且我在控制台中仍然收到相同的错误:items:1 Uncaught TypeError: Failed to resolve module specifier "bootstrap". Relative references must start with either "/", "./", or "../".

推荐答案

默认情况下,Rails使用导入映射,它不使用node_modules来查找包:

# config/importmap.rb

pin "bootstrap", to: "https://ga.jspm.io/npm:bootstrap@5.3.2/dist/js/bootstrap.esm.js"
pin "@popperjs/core", to: "https://ga.jspm.io/npm:@popperjs/core@2.11.8/lib/index.js"

或者使用importmap命令:

$ bin/importmap pin bootstrap
import * as bootstrap from "bootstrap"

// or just get what you need
import { Modal } from "bootstrap"

100

Ruby-on-rails相关问答推荐

安装特定版本的Ruby时出现问题(OpenSSL问题)

使用ImportMaps将HighLightJS添加到rails 7.1

为什么是 json.partial!使用新的哈希语法传递本地时,jbuiler 模板中的行不执行?

在 Datatable Ajax 调用中通过 Ajax 更新 div

Rails 和 jsonb 类型jsonb不存在

如何将动态 Ruby 代码嵌入到 Slim 模板中的javascript部分?

Rails 中的转义值(类似于 mysql_real_escape_string())

ActiveRecord 回调列表

使用 rails 3.1.0 和 ubuntu 安装 Nokogiri 1.5.0 时出错

Rails:使用 RSpec 测试命名范围

如何在 Rails 应用程序中使用长 id?

activerecord 查找所有未包含在数组中的内容

使用 rvm 更新 ruby​​ 版本后收到警告消息Path set to RVM

在rails国际化yml文件中传递变量

:javascript haml 标签中的内联Ruby ?

我怎样才能看到水豚在失败的黄瓜步骤中发现了什么?

用于在多行上链接调用的 Ruby 约定

sass-rails 助手image-url、asset-url在 rails 3.2.1 中不起作用

使用设计创建一个用户显示页面

在 Ruby on Rails 中设置日志(log)记录级别