I wanted to share with everyone some elm-review rules I’ve written for reviewing Elm ports and hopefully avoid a few pain points that I’ve come across learning to work with ports.
elm-review-ports
There are three rules in the package so far:
- NoDuplicatePorts - Ensure that port names are unique across your project.
- NoUnsafePorts - Forbid unsafe types in ports.
- NoUnusedPorts - Ensure that all defined ports have been used.
NoDuplicatePorts
As the name says, this rule checks for any duplicate port names in your project. When there are multiple ports with the same name you may encounter a javascript runtime error. I got one of these and it took me a little while to track down because I was writing Elm and wasn’t expecting to have a javascript runtime error so I didn’t immediately look into the javascript console.
NoUnsafePorts
Inspired by the information about Verifying Flags in the Elm guide, this rule reports any ports that do not send or receive a Json.Encode.Value
. You can set the rule to ignore outbound ports - since it’s a little safer to let javascript worry about type handling. This has been great for me already and has made me think about what I’m sending through my ports and how Elm can handle it best.
NoUnusedPorts
This rule reports any ports that are not used anywhere in the project. A port is only considered used if it can be traced to a main
function. Elm is very good at eliminating dead code from the compiled JavaScript. When a port is unused it will not be present in the compiled JavaScript, and when no ports are used the app.ports
object will be undefined
. This can lead to JavaScript runtime errors that could take you some time to figure out.
This was a surprisingly tricky rule to write as it takes quite a lot of effort to trace a function all the way to main
. One bonus of doing this though is that the rule can point at where it lost the trace. Here’s an example of what that report looks like: