Rails 7 Importmap Pins不兼容的Jquery源码

7cjasjjr  于 2023-08-04  发布在  jQuery
关注(0)|答案(2)|浏览(127)

提问

为什么由importmaps命令生成的源代码不能在Bootstrap 4.6.1中工作,而同一版本的jquery的修改后的源代码可以工作?

问题详情

我使用importmaps创建了一个rails7应用程序来管理JavaScript。
我正在importmap.rb中手动固定一个旧版本的Bootstrap(4.6.1)
当我运行bin/importmap pin jquery时,以下内容被添加到importmap.rb

pin "jquery", to: "https://ga.jspm.io/npm:jquery@3.6.0/dist/jquery.js"

字符串
加载站点并查看ChromeWebTools会显示此错误消息,并且下拉菜单和 accordion 等jquery功能无法正常工作

Uncaught TypeError: Bootstrap's JavaScript requires jQuery. jQuery must be included before Bootstrap's JavaScript.
    at Object.jQueryDetection (bootstrap.min.js:6:2464)


但是,当我在importmap.rb中手动更新jquery源代码时,

pin "jquery", to: "https://ga.jspm.io/npm:jquery@3.6.0/jquery.js"


错误消息被解决并且功能被恢复。
在我看来,这两个源代码几乎完全相同,都是jquery3.6.0

https://ga.jspm.io/npm:jquery@3.6.0/dist/jquery.js
https://ga.jspm.io/npm:jquery@3.6.0/jquery.js

工作配置

application.js

// Configure your import map in config/importmap.rb. Read more: https://github.com/rails/importmap-rails
import { Turbo } from "@hotwired/turbo-rails"
Turbo.session.drive = false
import "controllers"

import  "jquery";
import * as bootstrap from "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 "jquery", to: "https://code.jquery.com/jquery-3.6.0.min.js", preload: true
pin "bootstrap", to: "https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.min.js"
pin "@popperjs/core", to: "https://ga.jspm.io/npm:@popperjs/core@2.11.2/lib/index.js"

ar7v8xwq

ar7v8xwq1#

我有一个类似的设置,它的工作。使jQuery对整个页面可用,将application.js中的导入替换为:

import jquery from 'jquery'
window.$ = jquery

import * as bootstrap from 'bootstrap'
window.bootstrap = bootstrap

字符串

mzaanser

mzaanser2#

我一直在纠结这个问题,而解决这个问题的方法是:

  • importmap中添加Jquery
  • 现在,转到Rails配置路径“@hotwired/stimulus”来配置“jquery”:app/javascript/controllers/application.js
import { Application } from "@hotwired/stimulus"
...
import jQuery from "jquery"

window.jQuery = jQuery
window.$ = jQuery
...

字符串

  • 仅供参考,在我的情况下,它看起来像这样:
import { Application } from "@hotwired/stimulus"
import jQuery from "jquery"

const application = Application.start()

// Configure Stimulus development experience
application.debug = false
window.Stimulus   = application
window.jQuery = jQuery
window.$ = jQuery

export { application }

相关问题