Type-safety for ports when you want to slap some Elm<->JS interop quickly.
For a full-fledged Elm<->TS interop, you should choose elm-ts-interop
.
I've been writing a lot of personal-use scripts in Elm instead of vanilla JS/TS (because writing with type-safety, in a functional language, is a delightful experience most of the time), and find myself having to write lots of glue-code to get interop between Elm and NodeJS.
One common pattern is a unified port: one port for all incoming data and one port for all outgoing data.
So Harbor exists as a way for me to quickly get type-safe port messages in and out of Elm.
- Copy the
Harbor.elm
file into your project. - Define your
PortInMsg
andPortOutMsg
types. The file already has some good starting points to help you. It's no different from defining custom data types in Elm. - Define the
sendHandler
,receiveHandler
andportOutMsgToString
functions. Again, follow the lead in the example. The first two are encoders and decoders mostly. - Add a
PortMsg
type to your MainMsg
as show in theMain.elm
file and handle the incoming port msgs the way you want. - Add
harborSubscription
to your Mainsubscriptions
as shown in theMain.elm
file. - To send data out of a port, simply use
Harbor.send
as shown in the example inMain.elm
. - On the JS side, you can now send/receive a tuple of shape
["PortMsg", data]
where"PortMsg"
is the string representation of thePortInMsg
orPortOutMsg
types. Again, check theindex.js
file to see how that's done.
For full-fledged TS/Elm interop, that's the best option. But there maybe some use-cases for just copy-pasting code from Harbor:
- you are prototyping something "quick-n-dirty", or
- you don't want to deal with TS-config for what you are doing, or
- you are writing something simple and dont want to run a generator.