ReasonReact Playground
ReasonReact with editable source and live preview.
How it works
Going from ReasonML to JavaScript requires 3 transformation steps:
- Transform ReasonML to OCaml+JSX
- Transform OCaml+JSX to plain OCaml
- Compile OCaml to JS
Step 1
ReasonML code is transformed to OCaml+JSX by refmt-js.
Step 2
JSX syntax is handled by the version of reactjs_jsx_ppx_v2 recently landed in BuckleScript master branch. This version can be compiled by js_of_ocaml to be used in a web browser.
It exposes a jsxv2
object with a rewrite
method to perform the
transformation.
For example:
(button ~children:[ReasonReact.stringToElement "Hello!"] ()) [@JSX ]
Gets transformed to:
let _ =
ReactDOMRe.createElement "button"
[|(ReasonReact.stringToElement "Hello!")|]
If there are no errors in the input string, the output code is returned in a serialized JSON object, e.g.:
jsxv2.rewrite('(button ~children:[ReasonReact.stringToElement "Hello!"] ()) [@JSX ]')
Returns:
{
"ocaml_code": "let _ =\n ReactDOMRe.createElement \"button\"\n [|(ReasonReact.stringToElement \"Hello!\")|]"
}
Otherwise, you will get a serialized JSON object containing the error returned by the PPX preprocessor, e.g.:
jsxv2.rewrite('(button () /) [@JSX]')
Returns:
{
"ppx_error_msg": "Line 1, 12: Syntax error: operator expected.",
"row": 0,
"column": 12,
"endRow": 0,
"endColumn": 13,
"text": "Syntax error: operator expected.",
"type": "error"
}
Step 3
Pure OCaml code returned by Step 2 is compiled to JavaScript using the JS version of BuckleScript (also compiled by js_of_ocaml).
To load external modules, you can use the new load_module
method
recently
added to the JS API of BuckleScript. This methods loads an external module
given it's compiled .cmi
and .cmj
contents. It accepts these parameters:
cmi_path
:.cmi
path in the (JSOO) pseudo file-systemcmi_content
: binary serialization of the.cmi
filecmj_name
:.cmj
filenamecmj_content
: binary serialization of the.cmj
file
See this file for an example of how to load ReasonReact modules.
.cmi
and .cmj
contents can be serialized using this
utility.
See this
script
for an example of how to use bin2js
to generate externalModules.js
.
JavaScript code produced by BuckleScript needs React and ReasonReact to be evaluated, so we need to bundle those libraries with browserify (as it's done for the stdlib) using this script.
Acknowledgments
Based on:
Thanks to Hongbo Zhang and to Cheng Lou for reviewing my patches. Thanks to the Ocsigen team for developing js_of_ocaml.