title | description | canonical |
---|---|---|
Converting from JS | How to convert to ReScript with an existing JS codebase | /docs/manual/v11.0.0/converting-from-js |
ReScript offers a unique project conversion methodology which:
- Ensures minimal disruption to your teammates (very important!).
- Remove the typical friction of verifying conversion's correctness and performance guarantees.
- Doesn't force you to search for pre-made binding libraries made by others. ReScript doesn't need the equivalent of TypeScript's
DefinitelyTyped
.
Run npm install rescript
on your project, then imitate our New Project workflow by adding a rescript.json
at the root. Then start npx rescript -w
.
Let's work on converting a file called src/main.js
.
constschool=require('school');constdefaultId=10;functionqueryResult(usePayload,payload){if(usePayload){returnpayload.student;}else{returnschool.getStudentById(defaultId);}}
First, copy the entire file content over to a new file called src/Main.res
by using our %%raw
JS embedding trick:
<CodeTab labels={["ReScript", "JS Output"]}>
%%raw(`constschool=require('school');constdefaultId=10;functionqueryResult(usePayload, payload) {if (usePayload) {returnpayload.student; } else {returnschool.getStudentById(defaultId); }}`)
// Generated by ReScript, PLEASE EDIT WITH CARE'use strict';constschool=require('school');constdefaultId=10;functionqueryResult(usePayload,payload){if(usePayload){returnpayload.student;}else{returnschool.getStudentById(defaultId);}}/* Not a pure module */
Add this file to rescript.json
:
"sources": { "dir" : "src", "subdirs" : true },
Open an editor tab for src/Main.res.js
. Do a command-line diff -u src/main.js src/Main.res.js
. Aside from whitespaces, you should see only minimal, trivial differences. You're already a third of the way done!
Always make sure that at each step, you keep the ReScript output .res.js
file open to compare against the existing JavaScript file. Our compilation output is very close to your hand-written JavaScript; you can simply eye the difference to catch conversion bugs!
Let's turn the defaultId
variable into a ReScript let-binding:
<CodeTab labels={["ReScript", "JS Output"]}>
letdefaultId=10%%raw(`constschool=require('school');functionqueryResult(usePayload, payload) {if (usePayload) {returnpayload.student; } else {returnschool.getStudentById(defaultId); }}`)
// Generated by ReScript, PLEASE EDIT WITH CARE'use strict';constschool=require('school');functionqueryResult(usePayload,payload){ifusePayload{returnpayload.student}else{returnschool.getStudentById(defaultId)}}vardefaultId=10;exports.defaultId=defaultId;/* Not a pure module */
Check the output. Diff it. Code still works. Moving on! Extract the function:
<CodeTab labels={["ReScript", "JS Output"]}>
%%raw(`constschool=require('school');`)letdefaultId=10letqueryResult= (usePayload, payload) => { ifusePayload { payload.student } else { school.getStudentById(defaultId) } }
Format the code: ./node_modules/.bin/rescript format src/Main.res
.
We have a type error: "The record field student can't be found". That's fine! Always ensure your code is syntactically valid first. Fixing type errors comes later.
The previous type error is caused by payload
's record declaration (which supposedly contains the field student
) not being found. Since we're trying to convert as quickly as possible, let's use our object feature to avoid needing type declaration ceremonies:
<CodeTab labels={["ReScript", "JS Output"]}>
%%raw(`constschool=require('school');`)letdefaultId=10letqueryResult= (usePayload, payload) => { ifusePayload { payload["student"] } else { school["getStudentById"](defaultId) } }
Now this triggers the next type error, that school
isn't found. Let's use external
to bind to that module:
<CodeTab labels={["ReScript", "JS Output"]}>
@moduleexternalschool: 'whatever="school"letdefaultId=10letqueryResult= (usePayload, payload) => { ifusePayload { payload["student"] } else { school["getStudentById"](defaultId) } }
// Generated by ReScript, PLEASE EDIT WITH CARE'use strict';varSchool=require("school");functionqueryResult(usePayload,payload){if(usePayload){returnpayload.student;}else{returnSchool.getStudentById(10);}}vardefaultId=10;exports.defaultId=defaultId;exports.queryResult=queryResult;/* school Not a pure module */
We hurrily typed school
as a polymorphic 'whatever
and let its type be inferred by its usage below. The inference is technically correct, but within the context of bringing it a value from JavaScript, slightly dangerous. This is just the interop trick we've shown in the external
page.
Anyway, the file passes the type checker again. Check the .res.js
output, diff with the original .js
; we've now converted a file over to ReScript!
Now, you can delete the original, hand-written main.js
file, and grep the files importing main.js
and change them to importing Main.res.js
.
If you prefer more advanced, rigidly typed payload
and school
, feel free to do so:
<CodeTab labels={["ReScript", "JS Output"]}>
typeschooltypestudenttypepayload= { student: student } @moduleexternalschool: school="school" @sendexternalgetStudentById: (school, int) =>student="getStudentById"letdefaultId=10letqueryResult= (usePayload, payload) => { ifusePayload { payload.student } else { school->getStudentById(defaultId) } }
// Generated by ReScript, PLEASE EDIT WITH CARE'use strict';varSchool=require("school");functionqueryResult(usePayload,payload){if(usePayload){returnpayload.student;}else{returnSchool.getStudentById(10);}}vardefaultId=10;exports.defaultId=defaultId;exports.queryResult=queryResult;/* school Not a pure module */
We've:
- introduced an opaque types for
school
andstudent
to prevent misuse of their values - typed the payload as a record with only the
student
field - typed
getStudentById
as the sole method ofstudent
Check that the .res.js
output didn't change. How rigidly to type your JavaScript code is up to you; we recommend not typing them too elaborately; it's sometime an endless chase, and produces diminishing returns, especially considering that the elaborate-ness might turn off your potential teammates.
In the same vein of idea, resist the urge to write your own wrapper functions for the JS code you're converting. Use external
s, which are guaranteed to be erased in the output. And avoid trying to take the occasion to convert JS data structures into ReScript-specific data structures like variant or list. This isn't the time for that.
The moment you produce extra conversion code in the output, your skeptical teammate's mental model might switch from "I recognize this output" to "this conversion might be introducing more problems than it solves. Why are we testing ReScript again?". Then you've lost.
- Paste the JS code into a new ReScript file as embedded raw JS code.
- Compile and keep the output file open. Check and diff against original JS file. Free regression tests.
- Always make sure your file is syntactically valid. Don't worry about fixing types before that.
- (Ab)use object accesses to quickly convert things over.
- Optionally clean up the types for robustness.
- Don't go overboard and turn off your boss and fellow teammates.
- Proudly display that you've conserved the semantics and performance characteristics during the conversion by showing your teammates the eerily familiar output.
- Get promoted for introducing a new technology the safer, mature way.