为什么在使用资产主机时必须在本地预编译资产?

Why do i have to precompile assets locally when using an asset host?

我正在为我的 Rails 应用程序使用资产主机 (AWS Cloudfront):

# config/environments/production.rb
config.asset_host = "xxxxxxxxxxx.cloudfront.net"

在部署 CI 服务期间,我预编译了资产:

bundle exec rake assets:precompile

然后将这些生成的资产推送到作为 Cloudfront 分发源的 S3 存储桶。

注意:我没有在最终部署的 docker 映像中包含预编译资产。

现在,当我启动服务器并尝试访问它时 - 我收到错误消息:

application.css is not present in the asset pipeline

我知道 Whosebug 上有多个关于此特定错误消息的问题。但是 我什么都试过了 例如就像设置 config.assets.compile = true/false 但唯一让它起作用的是 在构建 中包含预编译资产(最终 docker 图像)。

所以现在我问自己:尽管我使用的是资产托管服务商,但我是否必须始终在本地包含资产?!

asset pipeline 解析资产路径的方式是首先查找资产文件的 fingerprinting(由 rake 任务 precompile 生成)然后映射到 asset_host(如果有),如果没有 fingerprinting 映射到资产,那么它将抛出异常,它不会检查您的 asset_host.

如果您不在 docker 图像中包含预编译资产,则 docker 容器中的 rails 应用无法找到资产文件,因为没有 fingerprinting 在该容器中生成。

所以是的,你必须这样做。

但是,您可以通过在资产路径前添加正斜杠或添加 skip_pipeline: true 来绕过 asset pipeline,在您的情况下,您已经生成指纹并将这些文件推送到您的资产主机所以你可以绕过,例如 application.css,像这样 stylesheet_link_tag '/application-{fingerprinting}.css',但显然这不是一个好的选择,因为你需要对所有文件都这样做。