【问题标题】:Do all the .ex files have to be in /lib folder when creating a mix project?创建混合项目时,所有 .ex 文件都必须在 /lib 文件夹中吗?
【发布时间】:2020-01-01 20:28:14
【问题描述】:

我生成了一个新的混合项目,我可以在 /lib 文件夹中看到 .ex 文件。尝试使用“mix run”从项目根路径运行应用程序时,由于文件位于 /lib 文件夹中,因此出现错误。 为了克服这个问题,我在项目根目录中创建了一个具有 start(_type,_args) 方法的新文件,我试图将该模块设置为我的 mix.exs 中的 mod 键,但它没有链接到指定的模块。

还有其他方法可以从项目根目录运行应用程序吗?

def application do
  [
    extra_applications: [:logger],
    mod: {Proj,[]}
  ]
end


def Proj do
  use Application

  def start(_type,_args) do
    Proj1.printHello() #calling the method from another module in /lib
  end
end

这是错误日志:

10:55:24.579 [info]  Application proj1 exited: exited in: Proj.start(:normal, [])
    ** (EXIT) an exception was raised:
        ** (UndefinedFunctionError) function Proj.start/2 is undefined (module Proj is not available)
            Proj.start(:normal, [])
            (kernel) application_master.erl:277: :application_master.start_it_old/4

【问题讨论】:

  • mod: {Proj, []} 行告诉 Elixir 使用哪个模块来启动您的应用程序。根据该错误消息,您在 lib 目录中没有名为 Proj 的模块。至于您最初的问题是否所有代码都需要进入lib,默认情况下是。如果需要,您可以configure 使用其他目录或附加目录。但是,您通常不需要这样做。
  • @JustinWood:我把它移到了 lib,当我运行 mix run 时它现在可以工作了。但是,当我尝试运行mix run proj.ex 时,它会打印输出并输出错误no such file。这可能是什么原因?
  • 您到底想用mix run my_file.ex 实现什么?
  • 我必须通过传递 2 个命令行参数来运行文件。现在,当我尝试运行 mix run my_file.ex arg1 arg2 时,它会打印输出,因为我已将模块配置为应用程序的起点,但它会打印此错误 - ** (Mix) No such file: proj1.ex。如果我只是做mix run arg1 arg2 它将 arg1 作为文件名。

标签: elixir


【解决方案1】:

只是为了让@kamil 所做的事情更具描述性。

defmodule Proj.MixProject do
  use Mix.Project

  def project do
    [
      # ...
      elixirc_paths: elixirc_paths(Mix.env())
    ]
  end

  # Specifies which paths to compile per environment.
  defp elixirc_paths(:test), do: ["lib", "test/support"]
  defp elixirc_paths(_), do: ["lib"]

【讨论】:

    【解决方案2】:

    您需要在mix.exs 文件中添加:

    defmodule Proj.MixProject do
      use Mix.Project
    
      def project do
        [
          # ...
          elixirc_paths: ["lib"]
        ]
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-14
      • 2020-10-27
      • 1970-01-01
      • 1970-01-01
      • 2012-07-17
      相关资源
      最近更新 更多