Let’s walk through the process of writing and publishing an Elixir library from start to finish. For illustrative purposes, we’ll create a pretend simple_statistics statistics toolkit for Elixir.
Note: if you need an actual statistics library check out statistics.
Mix will generate the following directory structure:
Write Code
You can create a new folder in lib/ with the name of your package (simple_statistics) to place other modules. It’s a good idea to split code to different modules for modularity. We’ll create a new lib/mean.ex module.
Write Documentation
Use @doc to specify docstrings. You should ideally document every major public function in your modules:
Add Doctests
You can add doctests in your docstrings like so:
To run them as part of your test suite:
Add Type Annotations
We can use Typespecs to utilize static type checking for our functions:
Typespecs helps ensure that there’s no discrepancy between differing types of our program’s constants, variables, and functions.
You can then perform static analysis by using dialyzer. First, update your mix.exs to add dialyxir as a dependency:
Then, run dialyzer - Erlang’s static analysis tool:
Generate Documentation
Update your mix.exs to add the following dependencies:
As you can see, our documentation also displays docstring examples as well as any type annotations. Cool!
Publishing your Library
We’re now ready to start publishing our library.
Register with Hex
First, you need to set up an account on Hex, Erlang and Elixir’s package manager:
Click on the email confirmation link to activate your Hex.pm acccount.
Set your project’s metadata
Update your mix.exs:
After the package metadata and dependencies have been added to mix.exs, we are ready to publish the package with the mix hex.publish command:
Note that this will be published as the version specified in mix.exs.
A published version can be amended or reverted with --revert up to one hour after its publication. If you want to revert a publication that is more than one hour old you need to contact an administrator.
Publishing Documentation
You can publish your documentation to Hex Docs. The documentation will be generated by running the mix docs task.
This documentation will be accessible at https://hexdocs.pm/my_package/1.0.0. In addition, https://hexdocs.pm/my_package will always redirect to the latest published version. Instead of Hex.pm, you can alternatively host the documentation at docs/ yourself or on Github Pages.
Appendix: Versioning
Publish a new version by updating the version value in mix.exs and running mix hex.publish.
Remember to use Git tags to annotate version changes!
In Closing
We’ve succesfully written and published an Elixir library! Writing and publishing libraries in Elixir is easy and straightforward. Other developers can now add your library into their deps and start using it in their projects.
Thanks for reading! Let me know if you have any feedback in the comments below.