有人在Rails 7中搞懂了importmaps吗?我遇到了一个难题。
如果我在开发环境下运行./bin/importmap json
,我会得到如下输出(正常情况):
{
"imports": {
"application": "/assets/application-a7fd3fc58be844f89656edec1ec73e18f9ab627e54b2aea67a97aad4613b6305.js",
"@hotwired/turbo-rails": "/assets/turbo.min-96cbf52c71021ba210235aaeec4720012d2c1df7d2dab3770cfa49eea3bb09da.js",
"@hotwired/stimulus": "/assets/stimulus.min-900648768bd96f3faeba359cf33c1bd01ca424ca4d2d05f36a5d8345112ae93c.js",
"@hotwired/stimulus-loading": "/assets/stimulus-loading-1fc59770fb1654500044afd3f5f6d7d00800e5be36746d55b94a2963a7a228aa.js",
"stimulus": "https://ga.jspm.io/npm:stimulus@2.0.0/dist/stimulus.umd.js",
"stimulus-use": "https://ga.jspm.io/npm:stimulus-use@0.41.0/dist/index.js",
"hotkeys-js": "https://ga.jspm.io/npm:hotkeys-js@3.8.8/dist/hotkeys.esm.js",
"trix": "/assets/trix-1563ff9c10f74e143b3ded40a8458497eaf2f87a648a5cbbfebdb7dec3447a5e.js",
"@rails/actiontext": "/assets/actiontext-28c61f5197c204db043317a8f8826a87ab31495b741f854d307ca36122deefce.js"
}
}
...而且我的JavaScript代码也可以正常运行。
然而,如果我在生产环境中运行相同的命令,就会得到以下结果:
{
"imports": {
"application": "/application.js",
"@hotwired/turbo-rails": "/turbo.min.js",
"@hotwired/stimulus": "/stimulus.min.js",
"@hotwired/stimulus-loading": "/stimulus-loading.js",
"stimulus": "https://ga.jspm.io/npm:stimulus@2.0.0/dist/stimulus.umd.js",
"stimulus-use": "https://ga.jspm.io/npm:stimulus-use@0.41.0/dist/index.js",
"hotkeys-js": "https://ga.jspm.io/npm:hotkeys-js@3.8.8/dist/hotkeys.esm.js",
"trix": "/trix.js",
"@rails/actiontext": "/actiontext.js"
}
}
...而且什么都不起作用(JavaScript),因为请求/application.js返回404,尽管奇怪的是,我可以看到部署时资产编译为带有指纹的文件在/assets目录中 - 只是应用程序随后试图使用原始脚本,这些脚本(位于app/javascript目录中)没有为应用程序提供服务。
顺便说一句,我正在使用render.com进行部署(虽然在Heroku中也发生了同样的问题)。构建脚本如下:
#!/usr/bin/env bash
# exit on error
set -o errexit
bundle install
bundle exec rake assets:precompile
bundle exec rake assets:clean
bundle exec rake db:migrate
在我的production.rb中,我按照渲染文档的要求编写了以下内容:
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? || ENV['RENDER'].present?
......在生产环境中会评估为真。 有什么想法吗?
config.assets.compile = true # default: false
已经让它在某种程度上工作了。但这只是一个临时解决方案,因为如 https://guides.rubyonrails.org/asset_pipeline.html 中所述,“此模式使用更多内存,性能比默认模式差,并且不建议使用。” 我很讨厌这种情况总是发生在 RoR 上:https://discuss.rubyonrails.org/t/rails-7-javascript-and-asset-pipeline-documentation-not-really-complete-and-fully-comprehensible/80480 - Jens Schmidt./bin/importmap pin tom-select
或./bin/importmap pin tom-select -- download
(如果您不想使用 CDN 托管的版本)将其添加到 importmap 中,然后您就可以在 JS 控制器中使用import TomSelect from "tom-select"
来使用它了。例如,在 StimulusJS 的 connect() 中,您可以执行new TomSelect(this.element, {});
。 - clarifdotenv-rails
gem没有被放在生产组中。现在它的代码如下:gem "dotenv-rails", "~> 2.7", :groups => [:development, :test, :production]
- g_t_m