fhunleth
Handling Elixir 1.17 compiler warnings on unused optional dependencies
I’m trying to reduce the number of Elixir 1.17 warnings in my projects, and I have questions with optional dependencies.
One example that triggers a new warning is Jason’s optional dependency on Decimal. If you create an empty project, add :jason to the dependencies and compile, you’ll see this:
==> jason
warning: Decimal.new/1 is undefined (module Decimal is not available or is yet to be defined)
│
94 │ decimal.new(string)
│ ~
│
└─ (jason 1.4.3) lib/decoder.ex:94:17: Jason.Decoder.float_decode_function/1
warning: struct Decimal.Error is undefined (module Decimal.Error is not available or is yet to be defined)
└─ (jason 1.4.3) lib/decoder.ex: Jason.Decoder.float_decode_function/1
warning: Decimal.to_string/2 is undefined (module Decimal is not available or is yet to be defined)
│
242 │ [?", decimal.to_string(value, :normal), ?"]
│ ~
│
└─ (jason 1.4.3) lib/encode.ex:242:18: Jason.Encode.struct/4
warning: Decimal.to_string/1 is undefined (module Decimal is not available or is yet to be defined)
│
231 │ [?", decimal.to_string(value), ?"]
│ ~
│
└─ (jason 1.4.3) lib/encoder.ex:231:18: Jason.Encoder.Decimal.encode/2
There’s code that silenced a similar warning previously, but Elixir 1.17 is smarter. This is really cool that it can be detected, but I was wondering if there was preferred way of resolving warnings like this.
For example, placing the following compile-time checks around the Decimal-using functions would silence the Jason warnings:
if Code.ensure_loaded(Decimal) == {:module, Decimal} do
def fun_that_uses_decimal() do
...
end
end
Since this comes up with other libraries too, I’d like to be consistent and I’m not sure if there are subtle gotchas that this introduces.
Most Liked
LostKobrakai
Code.ensure_loaded?/2 has been what I’ve seen quite consistently being used around optional dependencies over the years, e.g.:
fhunleth
Perfect. Thank you.







