ruby-on-railsassetshelperruby-on-rails-7import-maps

stylesheet_link_tag with path, not only the file name


I am adding some extra CSS/JS files into my vendor folder:

vendor/my_theme/css/app.css
vendor/my_theme/css/bundle.css
vendor/my_theme/js/app.js

They belong to an external theme I am integrating. I want to keep these assets separate from the assets of my app.

To import them in my template.html.erb, I have to add them in the manifest.js:

// app/assets/config/manifest.js
// Template
//= link_tree ../../../vendor/my_theme

Add the folders to the assets.rb:

# config/initializers/assets.rb
Rails.application.config.assets.paths << Rails.root.join("vendor/my_theme/css")
Rails.application.config.assets.paths << Rails.root.join("vendor/my_theme/js")

And now I can import them:

<!-- template.html.erb -->
<%= stylesheet_link_tag "bundle.css" %>
<%= stylesheet_link_tag "app.css" %>
<%= javascript_include_tag("app.js") %>

But it looks very fragile for me. There are chances, in the future, I'll create an app.css or an app.js, and then there will be a name conflict.

I am looking for how I can use a more extended path for the import helper tags. Like in here:

<%= stylesheet_link_tag "vendor/my_theme/css/app.css" %>
<%= stylesheet_link_tag "my_theme/css/app.css" %>

Nothing works

I have tried to change manifest.js:

//= link_tree ../../../vendor/my_theme .css .js // => error
//= link_directory ../../../vendor/my_theme/css .css
//= link_directory ../../../vendor/my_theme/js .js

Nothing work


Solution

  • This path is relative to one of Rails.application.config.assets.paths:

    <%= stylesheet_link_tag "my_theme/css/app.css" %>
    

    You need to have "my_theme/css/app.css" inside of an asset path:

    # config/initializers/assets.rb
    
    Rails.application.config.assets.paths << Rails.root.join("vendor/themes")
    
    // app/assets/config/manifest.js
    
    //= link_tree ../../../vendor/themes
    

    Move my_theme into vendor/themes directory:

    vendor/
    └── themes/
        └── my_theme/
            ├── css/
            │   └── app.css
            └── js/
                └── app.js