Standard Library

Advanced

Embed Raw JavaScript

We're introducing this last-resort escape hatch first, in case you're ever stuck trying the other more legitimate APIs and wanna move on. Here's how you can drop a chunk of JavaScript right into your BuckleScript file:

The {|foo|} syntax stands for OCaml/BuckleScript/Reason's multi-line, "quoted string" syntax. Think of them as the equivalent of JavaScript's template literals. No escaping is needed inside that string.

Careful with the OCaml/Reason syntax here. [%raw foo] allows you to embed an expression. For top-level declarations in OCaml/Reason, use [%%raw foo] (two %):

[%%raw "var a = 1"]
let f = [%raw "function() {return 1}"]

[%%raw "var a = 1"];
let f = [%raw "function() {return 1}"];

You can also pass a function declaration with a string body in raw:

let f: (int -> int -> int) = [%raw fun a b -> "{return a + b}"]

let f: (int, int) => int = [%raw (a, b) => "{return a + b}"];

Output:

var f = function (a,b){{return a + b}};

If you have to use raw in the first place, then prefer this format when you're passing a function. This allows the compiler to understand that it's a function, to see the number of arguments it has, to detect some side-effects and to generate better JS code. Also note that while the function's type annotation ((int -> int -> int) in the preceding OCaml example) is not strictly required, it gives the compiler a better chance to understand your raw JavaScript, and you may get a compiler warning without it.