如何在Rails7中使用importmap来固定npm、yarn包?
我很高兴能够使用 Rails7,尤其是我们终于摆脱了 webpacker。 然而,今天当我尝试尝试 Rails7 时,我不再了解如何捆绑 javascript 脚本......并且那里没有教程或者我只是找不到它。
例如,我想导入 jquery 所以我运行
yarn add jquery
然后我写道:
// application.js
//importmap-rails
import "@hotwired/turbo-rails"
import "controllers"
import jquery from 'jquery'
但它不起作用, 然后我阅读了 importmap-rails 上的自述文件,然后我运行了
./bin/importmap pin jquery
它在 config/importmap.rb
pin "jquery", to: "https://ga.jspm.io/npm:[email protected]/dist/jquery.js"
它有效,但是,这并不是我所期望的。我希望 jquery 来自 node_modules/ 而不是 CDN
我怎样才能实现这一点?导入我从yarn/npm安装的npm包? 或者只是指出我在哪里可以找到有关如何在 Rails7 中使用 javascript 的文档?
I am very excited to use Rails7 especially that we finally get rid of webpacker.
However, today when I tried to try Rails7, I didn't get how to bundle javascript scripts anymore... and there wasn't tutorial there or I just could not find it.
For example, I wanted to import jquery so I ran
yarn add jquery
and then I wrote:
// application.js
//importmap-rails
import "@hotwired/turbo-rails"
import "controllers"
import jquery from 'jquery'
But it didn't work,
then I read the readme on importmap-rails, and I ran
./bin/importmap pin jquery
then it added a line in config/importmap.rb
pin "jquery", to: "https://ga.jspm.io/npm:[email protected]/dist/jquery.js"
It worked, however, it was not what I expected exactly. I wanted the jquery came from node_modules/ instead of CDN
How can I achieve that? To import npm packages that I install from yarn/npm?
Or just point out where I can find documents about how to use javascript in Rails7?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将下载它。
与javascript合作
(有关js的处理,但几乎没有有关importMap的信息)
importmap-rails 在Github上(更多有关ImportMap的信息)
will download it.
Working with JavaScript in Rails
(about dealing with JS but little info about importmap)
importmap-rails on GitHub (more info about importmap)
我相信您可以手动更新您的
config/importmap.rb
文件以阅读说,我相信用importMaps做出的设计决策可能不包括NPM或YARN。我相信ImportMaps代表了在WebPacker/Yarn/npm之外处理JavaScript的另一种方法。
I believe you can manually update your
config/importmap.rb
file to readThat being said, I believe the design decisions made with importmaps may not include npm or yarn. I believe importmaps represents an alternative method for handling javascript outside of webpacker/yarn/npm.
引用自 DHH:
因此,
importmap-rails
旨在替代package.json
。您可以使用 CDN 或将依赖项提交到/vendor/javascript
(v2 默认值),但由于安全隐患,我认为这两种选择都不是好的选择:但是这是设计使然,您不应该(也不能)从 node_modules 固定。
Quote from DHH:
So
importmap-rails
is meant as a replacement forpackage.json
. You can either use a CDN or commit dependencies to/vendor/javascript
(v2 default) although I think neither are good options because of security implications:But this is by design and you shouldn't (and can't) pin from node_modules.