Search code examples
elixirphoenix-framework

Path and name of CSS file in production so that I can inline it


In Phoenix 1.7 the file root.html.heex uses the following line to link to the CSS:

<link phx-track-static rel="stylesheet" href={~p"/assets/app.css"} />

How can I inline the compiled CSS asset in the production environment within an <style> element and still use the above version in the development environment?

I am searching for something like this:

<style>
  <%= File.read!("app.css") %>
</style>

But that doesn't work. How can I figure out the correct path and filename for the build CSS file?


Solution

  • <% css_file_name = "#{Application.app_dir(:xyz)}/priv/static/assets/app.css" %>
    
    <%= if File.exists?(css_file_name) do %>
      <style>
        <% {:ok, css} = File.read(css_file_name) %>
        <%= raw css %>
      </style>
    <% else %>
      <link phx-track-static rel="stylesheet" href={~p"/assets/app.css"} />
    <% end %>