You are currently looking at the v6.0 - v8.2 docs (Reason v3.6 syntax edition). You can find the latest manual page here.
(These docs are equivalent to the old BuckleScript docs before the ReScript rebrand)
Import from/Export to JS
// Import nodejs' path.dirname [@bs.module "path"] external dirname: string => string = "dirname"; let root = dirname("/User/github"); // returns "User"
Here's what the
[@bs.module "path"]: pass the name of the JS module as a string; in this case,
"path". The string can be anything:
external: the general keyword for declaring a value that exists on the JS side.
dirname: the binding name you'll use on the ReScript side.
string => string: the type signature of
= "dirname": the name of the variable inside the
pathJS module. There's repetition in writing the first and second
dirname, because sometime the binding name you want to use on the ReScript side is different than the variable name the JS module exported.
By omitting the string argument to
bs.module, you bind to the whole JS module:
[@bs.module] external leftPad: string => int => string = "./leftPad"; let paddedResult = leftPad("hi", 5);
default. You'd bind to it like this:
[@bs.module "./student"] external studentName: string = "default"; Js.log(studentName);
We support 2 JS export formats:
CommonJS (usable from JS as
ES6 modules (usable from JS as
import * from 'myFile').
The output format is configurable in bsb.
If your JS project is using ES6 modules, you're likely exporting & importing some default values:
// student.js export default name = "Al";
// teacher.js import studentName from 'student.js';
Technically, since a ReScript file maps to a module, there's no such thing as "default" export, only named ones. However, we've made an exception to support default module when you do the following:
/* FavoriteStudent.re */ let default = "Bob";
You can then require the default as normal JS side:
// teacher2.js import studentName from 'FavoriteStudent.js';
Note: the above JS snippet only works if you're using that ES6 import/export syntax in JS. If you're still using
require, you'd need to do:
let studentName = require('FavoriteStudent').default;