How do I use external JavaScript libraries in Elm?

I recently tested Elm for a project but ran into several problems: one of them is using external JS libraries with Elm (like Moment.js, i18n, firebase, etc.). I tried the example below, but it doesn't exactly answer what I want:

https://gist.github.com/evancz/e69723b23958e69b63d5b5502b0edf90

According to the example, I have to create separate programs to unload the module and create static .js files for each one. Is it possible to just write all the ports in one file and what are the recommendations to use the port?

+3


source to share


1 answer


According to the example, I have to create separate programs just to take the module out of the module and create static .js files for each one.

I don't believe it's true. The spelling example you are linking to is only intended to serve as an example of ports usage. You don't need to compile every part of your program that uses a port into its own separate .js file.

You can put all ports in one module, but I wouldn't do that. In my opinion, the best approach would be to have one port module for every external JS library you want to use, and put all the ports you use to communicate with that library in that module. Thus, the responsibility for each such module is clear. Then compile the Elm app, port modules and everything into one .js file.



What are the best practices for using the port?

Ok, this is a little open. However, from my somewhat limited experience:

  • Keep port handling in separate modules, and don't declare the module as port module

    if you don't need to.

  • Make sure you thoroughly test the integration with third party libraries, in particular with bugs. Elm will throw an exception if the data type coming through the port from the external library back to Elm is not as you stated.

  • If you can find an Elm package that does the exact same thing as an external JS library, consider using that.

+3


source







All Articles