简体   繁体   中英

How do you define a mix task in an exs file and still run it the same?

If I had a mix task such as the following defined in hello.ex, it runs fine.

defmodule Mix.Tasks.Hello do
  use Mix.Task
  def run(_), do: IO.puts "hello"
end

But this doesn't seem possible in a "hello.exs" type file? Or is there a way to have a mix task without the ".ex" extension.

I am not sure what do you mean by “without compilation.” Elixir is indeed a compiled language, it's unable to execute anything without compilation.

In addition to the Elixir file extension .ex , Elixir also supports .exs files for scripting. Elixir treats both files exactly the same way, the only difference is in intention. .ex files are meant to be compiled while .exs files are used for scripting. When executed, both extensions compile and load their modules into memory , although only .ex files write their bytecode to disk in the format of .beam files.
https://elixir-lang.org/getting-started/modules-and-functions.html#scripted-mode

mix is an external application to your code. It requires a .beam file to execute it, or it has to load the compiled script into its process memory .

So, technically you might do somewhat like

defmodule Mix.Tasks.Hello do
  use Mix.Task
  def run(_), do: IO.puts "hello"
end

defmodule Mix.Tasks.Wrapper do
  use Mix.Task
  def run(task) do
    Code.compile_file("hello.exs")
    Mix.Task.run(Module.concat(task))
  end
end

But why ? What would be wrong with having the task as .ex file?

Also, you might achieve something similar with a help of Code.compile_string/2 to compile the task and load it into mix process' memory, but again, that's not how it's intended to be used.

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