简体   繁体   English

生产环境中的 Mix.env/0 等效项?

[英]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. Mix.env/0 在mix phoenix.server中正常工作,但在使用 exrm 构建的生产环境中调用失败。 It makes sense because mix isn't included in the release build, but is there any equivalent of Mix.env/0?这是有道理的,因为 mix 不包含在发布版本中,但是有没有 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:我在一些代码中像这样使用 Mix.env/0 :

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然后您可以使用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:您可以像这样在编译时将 Mix.env/0 作为模块常量唤起:

@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:我知道这真的很晚了,但是根据程序是在生产模式还是在开发模式下运行不同的配置文件的一种方法是将其添加到config.exs文件的最后一行:

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 .您可以在此处了解更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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