简体   繁体   中英

Elixir script with dependency

I'm writing a quick Elixir script, and I'd like to use a csv library dependency. It seems a bit overkill to create a new mix project just to add in dependency management for this one library. What would you recommend? Would you go the mix project route for a simple script with a dependency?

EDIT

Note: I'm not asking how to install and access dependencies globally. The question is, "would you go the mix project route..." What is the suggested approach?

Go the mix project route. Quick and dirty scripts have a way of growing into bigger projects.

Introduced as an experimental feature in Elixir 1.12, Mix.install/2 now allows you to specify a dependency directly in an Elixir script, giving you an alternative to a full-blown mix project.

Usage is quite straightforward: list your dependencies at the top of your script (in the same format that is returned from the regular deps function in a mix project), and it will take care of downloading, compiling, and caching the dependencies for you:

Mix.install([
  {:httpoison, "~> 1.8"},
  :jason
])
HTTPoison.start
IO.puts(Jason.encode!(%{hello: :world}))
...

It is possible to do this by using using Code.require_file/2

Eg consider this:

# foo.ex
defmodule Foo do
  def bar, do: "Barrrr"
end

and then, in the same directory, put your script:

# main.exs
Code.require_file("foo.ex", __DIR__)

Foo.bar()
|> IO.puts()

You can tweak that to include some other 3rd party file that you manually put in your directory, but it isn't very idiomatic ! You're unlikely to see something like the above ever (in fact, I just made it up). As previously noted, you're usually better off sticking to a Mix project (perhaps make a custom mix task).

Remember that Elixir is first and foremost a virtual machine (the Erlang VM), so it always brings along that "baggage". For quick one-off scripts where portability is the top priority, Elixir may not be the best choice. I might reach for Python for simple scripts (because rather than carrying its own baggage, it assumes your computer has all this stuff lying around), or Go (because it would compile any complexities into a single executable).

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