如何使用 importmap 在 Rails 7 中安装 jQuery?

How can I install jQuery in Rails 7 with importmap?

我有一个新的 Rails 7 应用程序。我目前正在尝试学习自 Rails 5 以来的所有新功能。我想在我的 javascript 文件中使用以下代码,但到目前为止我收到以下错误:Uncaught ReferenceError: $ is not defined.

$(document).on("turbo:load", () => {
  console.log("turbo!");
});

这是另外两个相关文件。如果我需要 post 任何其他信息,请告诉我。

importmap.rb

pin "application", preload: true
pin "jquery", to: "https://ga.jspm.io/npm:jquery@3.6.0/dist/jquery.js", 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 "el-transition", to: "https://ga.jspm.io/npm:el-transition@0.0.7/index.js"

pin_all_from "app/javascript/controllers", under: "controllers"

application.js

import "@hotwired/turbo-rails"
import "jquery"

$(document).on("turbo:load", () => {
  console.log("turbo!");
});

我需要在我的 application.js 文件中添加几行。

import "@hotwired/turbo-rails"
import jquery from "jquery"
window.jQuery = jquery
window.$ = jquery

使用 jspm 时 jQuery 必须显式导入:

// app/javascript/application.js

import jQuery from "jquery";

// NOTE: make jQuery global if needed
window.$ = window.jQuery = jQuery;

console.log($); // ok

另一种方法是切换到jspm以外的CDN:

# config/importmap.rb

# NOTE: pin jquery to jsdelivr instead of jspm
pin "jquery", to: "https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.js"
// app/javascript/application.js

import "jquery";
console.log($); // ok

相关: