How to conditionally compile a module with 3rd party macros

I’ve been working on a wrapper library for a brazillian Open Finance api, and I incurred into a fun error whilst trying to conditionally compile a module with 3rd party macros. I wrote a short text about this on medium, if you’re interested in the full story.

Also, I’m not too sure if ‘conditionally compiling a module’ is the best way to call this, but it’s how I’m able to describe this issue.

The code that errored looked a little like this:

  defmodule ConditionallyRunCode do
    if Code.ensure_loaded?(Phoenix.LiveView) do
      use Phoenix.Component
    else
      raise "no module 🤷"
    end
  end

and returned this error:

    error: module Phoenix.Component is not loaded and could not be found
    │
 36 │     require Phoenix.Component
    │     ^
    │
    └─ lib/pluggy/connect/live.ex:36:5: Pluggy.Connect.Live (module)

As weird as it looks, the solution was to define modules inside the if statement, and I briefly explain the reason why in my medium text, but the solution looked like this:

  if Code.ensure_loaded?(Kino.JS.Live) do
    defmodule ConditionallyCompileCode do
      use Kino.JS.Live
    end
  else
    defmodule ConditionallyCompileCode do
      raise "no module 🤷"
    end
  end

I didn’t really like how this solution looks, so I’d like to hear from the community:

Have you ever encountered an error like mine? Is there a better way to solve this issue?