| title | Embed Raw JavaScript |
|---|---|
| description | Utility syntax to for raw JS usage in ReScript |
| canonical | /docs/manual/embed-raw-javascript |
| section | JavaScript Interop |
| order | 2 |
First thing first. If you're ever stuck learning ReScript, remember that you can always just paste raw JavaScript code into our source file:
<CodeTab labels={["ReScript", "JS Output"]}>
%%raw(`
// look ma, regular JavaScript!
var message = "hello";
function greet(m) {
console.log(m)
}
`)// look ma, regular JavaScript!
var message = "hello";
function greet(m) {
console.log(m);
}The %%raw special ReScript call takes your code string and pastes it as-is into the output. You've now technically written your first ReScript file!
(The backtick syntax is a multiline string. No escaping is needed inside the string.)
While %%raw lets you embed top-level raw JS code, %raw lets you embed expression-level JS code:
<CodeTab labels={["ReScript", "JS Output"]}>
let add = %raw(`
function(a, b) {
console.log("hello from raw JavaScript!");
return a + b
}
`)
Console.log(add(1, 2))var add = function (a, b) {
console.log("hello from raw JavaScript!");
return a + b;
};
console.log(add(1, 2));The above code:
- declared a ReScript variable
add, - with the raw JavaScript value of a function declaration,
- then called that function in ReScript.
Existing JavaScript code can live inside ReScript files during migration.
You can also drop a %debugger expression in a body:
<CodeTab labels={["ReScript", "JS Output"]}>
let f = (x, y) => {
%debugger
x + y
}function f(x, y) {
debugger;
return (x + y) | 0;
}Output:
function f(x, y) {
debugger; // JavaScript developer tools will set an breakpoint and stop here
x + y;
}Embedding raw JS snippets isn't the best way to experience ReScript, though it's also highly useful if you're just starting out. As a matter of fact, the first few ReScript projects were converted through:
- pasting raw JS snippets inside a file
- examining the JS output (identical to the old hand-written JS)
- gradually extract a few values and functions and making sure the output still looks OK
At the end, we get a fully safe, converted ReScript file whose JS output is clean enough that we can confidently assert that no new bug has been introduced during the conversion process.
See the Converting from JS guide for a detailed walkthrough.