How do I load an elixir library in a simple elixir script?

谁说胖子不能爱 提交于 2019-12-21 11:34:09

问题


In ruby scripts, I could simply do:

require 'some-gem'

SomeGem.do_something!

How can I do something similar in elixir exs scripts without creating a brand new mix project? So far I've searched google on ways to do this, and read a few blog posts (such as this), but can't figure out a proper (read 'simple') way to do this.

Specifically, I want to use HTTPoison in my elixir script.


回答1:


There are no global package installs in Elixir like there are in Ruby. While it might be technically possible to compile the dependencies into .beam files and add them to the load path of your scripts (like the article you linked to does), if you want behavior somewhat similar to Ruby, I would recommend you to make use of mix run to run arbitrary scripts with all the project dependencies loaded.

Create one global mix project with all the dependencies you want specified in mix.exs, write your code in any .exs file (doesn't have to be in the same folder), and execute it by

cd /path/to/mix/project && mix run /path/to/.exs

You could even create a wrapper shell script to automatically do the above by just invoking my-elixir script.exs.

(I regularly do this while testing code for answers here on StackOverflow which use some common dependencies like HTTPoison and/or Poison.)




回答2:


Without mix, this could be a little complex, but doable.

I think you have to explicitly adding the path where HTTPoison is compiled on the top of your exs script.

Elixir provides an API Code.expand_path to prepend a path to the beginning of the Erlang VM code path list. You could find more description about the API here.




回答3:


By using erun, you can virtually install global Mix packages.

https://github.com/s417-lama/erun



来源:https://stackoverflow.com/questions/37679629/how-do-i-load-an-elixir-library-in-a-simple-elixir-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!