Reputation: 5462
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.
Upvotes: 0
Views: 688
Reputation: 121000
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.
Upvotes: 1