如何在 Rails 的供应商子文件夹中获取资产?

Art*_*dad 3 ruby ruby-on-rails vendor asset-pipeline

我需要在我的应用程序中安装一系列库,将它们保存在各自的文件夹中 /vendor/plugins/

例如,ckeditor 库:

  • 主文件夹在 /vendor/plugins/ckeditor/
  • js文件在 /vendor/plugins/ckeditor/js/Chart.js
  • css文件在 /vendor/plugins/ckeditor/css/chart.min.css

这样我就可以像这样导入到我的 application.scss 中:

*= require chart.min
Run Code Online (Sandbox Code Playgroud)

在我的 application.js 中是这样的:

//= require Chart.js
Run Code Online (Sandbox Code Playgroud)

当我尝试这样做时,rails 只访问文件夹/vendor/assets/plugins/插件,产生错误:

could not find file 'chart.min' with type 'text/css'
Run Code Online (Sandbox Code Playgroud)

如何让项目扫描所有供应商的子文件夹,直到找到我要导入的文件?

max*_*max 5

首先将/vendor/plugins目录添加到资产加载路径:

module MyApp
  class Application < Rails::Application
    config.assets.paths << Rails.root.join("vendor", "plugins")
    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration should go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded.
  end
end
Run Code Online (Sandbox Code Playgroud)

但是,将目录添加到资产加载路径并不意味着 Sprockets 将递归搜索所有子目录。将其配置为这样做也不是一个好主意。

您仍然需要提供从/vendor/plugins.

应用程序/资产/javascripts/application.js:

//= require ckeditor/js/Chart
Run Code Online (Sandbox Code Playgroud)

应用程序/资产/样式表/application.css:

*= require ckeditor/css/chart.min
Run Code Online (Sandbox Code Playgroud)

或者您可以只使用Rails 集成 gem并跳过所有麻烦。