简体   繁体   中英

Mix.env/0 equivalent in production env?

Mix.env/0 works correctly in mix phoenix.server , but it fails to call in a production environment which is built with exrm. It makes sense because mix isn't included in the release build, but is there any equivalent of Mix.env/0?

(UndefinedFunctionError) undefined function Mix.env/0 (module Mix is not available)

I'm using Mix.env/0 like this in some code:

if Mix.env == :dev do
  # xxxxxx
else
  # xxxxxx
end

You can simply define a config value for the environment:

config/prod.exs

config :my_app, :environment, :prod

config/dev.exs

config :my_app, :environment, :dev

You can then check that value using Application.get_env/3

if Application.get_env(:my_app, :environment) == :dev do

However, I would recommend giving this more context. Let's say you want to conditionally apply an authentication plug in production, you could set the config to:

config :my_app, MyApp.Authentication,
  active: true

if Application.get_env(:my_app, MyApp.Authentication) |> Keyword.get(:active) do
  #add the plug

This way, your conditions are feature based instead of environment based. You can turn them on and off regardless of environment.

You can evoque Mix.env/0 as a module constant at compile time like this:

@env Mix.env
#...
if @env == :dev do
#...

Works like a charm with releases.

I know this is really late, but one way of having different config files depending of whether the program is running in production or in development mode is by adding this to the last line of your config.exs file:

import_config "#{config_env()}.exs"

This will import specific config files depending on which mode the application is running. You can learn more about that here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM