Introduce the dynamic import (see forum RFC, GitHub discussion)
In this guide, we’ll explain how to use the dynamic import for module and module value. This new feature allows you to express the dynamic import syntax in Javascript in ReScript without having to be concerned about the actual file names and paths. We’ll go through several examples to help you to understand how to use this feature.
- Importing a module value
let forEach = await Js.import(Belt.Array.forEach)
let _ = [1, 2]->forEach(_ => ())
compiled to
var forEach = await import("rescript/lib/es6/belt_Array.js").then(function (m) {
return m.forEach;
});
Curry._2(forEach, [1, 2], (function (param) { }));
- Importing a module
module M = await Belt.Array
let forEach2 = M.forEach
let _ = [1, 2]->forEach2(_ => ())
compiled to
var M = await import("rescript/lib/es6/belt_Array.js");
var forEach2 = M.forEach;
Curry._2(forEach2, [1, 2], (function (param) { }));
- Lazy importing a React.component
In cases where React components need to be lazy-loaded, you can use the following approach:
// LazyComponent.res
@react.component
let make = () => React.string("Lazy")
// App.res
module LazyC = await LazyComponent
let c = <LazyC />
FYI, the syntax surface is still a work in progress, so if you apply formatting, the @res.await
used before the module may disappear. To test, simply turn off formatting.
EDIT: The await Module syntax has now been added as following binaries.
You can test using the built binaries available at the following address: Dynamic import · rescript-lang/rescript-compiler@6f0c22a · GitHub