Elixir Deps Without Mix Project

Sometimes we need to write a quick script to get a job done, chances are you might reach for bash or node for this task. As of Elixir 1.12 it’s now possible to install dependencies without creating a Mix project making it a great candidate for your scripting needs.

We can call Mix.install/1 at the top of an elixir script. The given deps should be in the same format as defined in a regular Mix project. The dependencies will be cached so if you run your script again and the dependencies haven’t changed then there won’t be any unnecessary downloads.

We can test this out by creating a script with the .exs extension. The first thing the script does is fetch dependencies that haven’t already been cached, after that the script will execute as normal with the dependencies available.

# halloween_countdown.exs
Mix.install([:timex])

days_until = fn (date) ->
  Timex.diff(date, Timex.now(), :days)
end

IO.puts("🎃 Halloween is in #{days_until.(~D[2021-10-31])} days!")

Now we can run this script like any other elixir script elixir halloween_countdown.exs and confirm everything works as expected.

Script result

Matthew Henley

🖥 Software engineer. React, Elm and Elixir enthusiast 🐣