Search code examples
ffireasonbucklescript

Using ReasonML FFI


I'm trying to understand ReasonML's FFI (i.e. external) usage. To that end, I put together the following code (see Try ReasonML and Sketch.sh)

type dom;
type element;
[@bs.val] 
external dom: dom = "document";
[@bs.send.pipe : dom]
external get_by_id: string => element = "getElementById";
let tag = document |> get_by_id("main");

However, the code currently fails with the errors:

Try ReasonML Error

We've found a bug for you! OCaml preview 6:11-18

The value document can't be found

Sketch.sh Error

Error: External identifiers must be functions

Would appreciate help in answering the following questions:

  1. What are the issues with the code above?
  2. I believe there are multiple ways to configure the FFI above, e.g. using [@bs.scope] - what implications, if any, are there from those ways? -- See follow-up question.

Solution

  • There are several different problems here:

    1. You use an identifier called document in the last line, but have not defined any such identifier. Instead you have assigned the name dom to reference document on the JavaScript side. The last line should therefore be let tag = dom |> get_by_id("main");.

    2. This will unfortunately still not work in "Try Reason", however, because it runs the code in a Web Worker which does not have access to document.

    3. Sketch.sh does not use BuckleScript and therefore does not understand BuckleScript FFI annotations. You can however use https://nit.sketch.sh/, which does.