Module Routes is not available or is yet to be defined

Context:

I have developed a game server backend in a single phoenix project. It has grown in complexity and size over last 3 years. I want to split the project into multiple projects like model, admin web , api web, realtime web, customisations runtime, etc.

I am trying to split my project into smaller projects similar to phoenix_live_dashboard.

While doing so I had this error - module Routes is not available or is yet to be defined

--- web.ex ---
defp view_helpers do
    quote do
      # Use all HTML functionality (forms, tags, etc)
      use Phoenix.HTML

      # Import basic rendering functionality (render, render_layout, etc)
      import Phoenix.View

      import IndyAdminWeb.ErrorHelpers
      import AdminWeb.Gettext
      # original - alias AdminWeb.Router.Helpers, as: Routes
      
      # This works - alias unquote(Application.get_env(:admin, :router)), as: Routes
      
      # Below code does not work - 
      if Mix.env() in [:dev, :test] do
        alias AdminWeb.Router.Helpers, as: Routes  
      end
    end
  end

Mix.env() based alias gives an error,

Routes.static_path/2 is undefined (module Routes is not available or is yet to be defined)

So I tried below the router from config and it works.

alias unquote(Application.get_env(:admin, :router)), as: Routes

What am I missing in case of if Mix.env() scenario. Why does it fail with Routes is not available.

Edited: couple of sentences for clarity.

Can you show us the error log?

1 Like

Also it’s showing here that you need to define a router like this

  def router do
    quote do
      use Phoenix.Router
    end
  end

alias, import, and friends are lexical. This means that if you define an alias inside an if, it will be valid only inside that if branch, only inside that nesting.

One way to think about it is that they behave like variables. A variable defined inside an if is not available outside of the if. The same applies to aliases and imports.

4 Likes

Thank you Jose. The only way to alias Router here is using alias unquote(Application.get_env(:admin, :router)), as: Routes ? Do you see any other way?

1 Like

That’s the way. You can also move the conditional to outside of the quote.

1 Like

Siddanth, web.ex has router defined, I truncated the file for brevity. Thank you.

Thank you.