Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to use a javascript library in elm?

Tags:

elm

I am working with Elm. I have read about ports in Elm and how they can help in sharing data/messages between Elm and Javascript.

I am intending to work with a rich datetime library like moment.js. Suggest how to port moment.js or any other alternatives for this?

like image 998
Gaurav Agarwal Avatar asked Dec 30 '14 07:12

Gaurav Agarwal


2 Answers

There aren't any rich datetime libraries for Elm (AFAIK), so let's go with porting.

I took a quick look at this JavaScript library and it looks like most of its functionality doesn't rely on the current date/time, which I expect is the only side-effect used in a datetime library. So Elm ports are not going to be very helpful.

Solution 1 - translate the JS code to Elm code

This will obviously take some time, but should be fairly simple since it's mostly side-effect-free code.

Solution 2 - Native Elm library (No longer supported)

Update: Creating your own native modules is no longer supported starting with Elm 0.19.

Since most functions are pure, you might be best of writing a Native library. This way the functions from the moment.js can map one-to-one on functions in Elm.

Warning: Native libraries are generally discouraged.
The reason is that it's really an unsafe way to directly call JavaScript functions, no compiler checks, you can introduce arbitrary side effects, which would mess up the language. So it's not ideal. But if you make sure you only bind to pure functions from the JavaScript library, you can get away with it.
Have a look at an example native library, like elm-markdown to see how to write one. You will need the "native-modules": true indication in the elm-package.json file. If you want to publish the library on package.elm-lang.org it will need to be checked and approved first. You can ask for that on the mailing list.

like image 159
Apanatshka Avatar answered Sep 27 '22 23:09

Apanatshka


Don't rewrite the library in Elm. Elm plays nicely with the external world. Take a look at Elm Ports: https://guide.elm-lang.org/interop/ports.html

like image 23
Juanda Avatar answered Sep 27 '22 22:09

Juanda