只需切换到CDN即可jspm, jQuery导入时将是全球性的:
# config/importmap.rb
# NOTE: pin jquery to jsdelivr instead of jspm
pin "jquery", to: "https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.js"
// app/javascript/application.js
import "jquery"; // this import first
import "script"; // then your other imports that use `$`
// NOTE: don't use relative imports: `import "./script"`
// add `pin "script"` to `importmap.rb`
console.log($); // ok
// app/javascript/script.js
console.log($) // ok
一切都正常,一次导入,多次导入,jquery 插件。无需额外吊装。
使用jspm时,jQuery必须在需要时显式导入,就像任何其他模块一样:
// app/javascript/place_where_i_need_jquery.js
import $ from "jquery";
// NOTE: don't make jQuery global, this only kind of works.
// window.$ = window.jQuery = $;
console.log($); // ok
澄清并提出window
休息的事情。它适用于stimulus,因为控制器是imported具有动态的import()
它通常在 jquery 加载后运行,并且有时间将其分配给window,但这并不能保证。这就是为什么你必须做吊装工作以确保$
在任何其他进口之前成为全球性的。
请记住,默认情况下导入映射是延迟的,因此您不能使用$
在你的内联脚本中(不是没有向后扭转你的手臂),因为 jquery 是在页面加载后加载的。