Skip to content

Commit 728b7f6

Browse files
zthfhammerschmidt
authored andcommitted
dynamic imports docs (rescript-lang#741)
1 parent 8708b52 commit 728b7f6

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

pages/docs/manual/latest/import-from-export-to-js.mdx

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,65 @@ var studentName = Student;
9393

9494
</CodeTab>
9595

96+
## Dynamic Import
97+
Leveraging JavaScript's [dynamic `import`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import) to reduce bundle size and lazy load code as needed is easy in ReScript. It's also a little bit more convenient than in regular JavaScript because you don't need to keep track of file paths manually with ReScript's module system.
98+
99+
### Dynamically Importing Parts of a Module
100+
Use the `Js.import` function to dynamically import a specific part of a module. Put whatever `let` binding you want to import in there, and you'll get a `promise` back resolving to that specific binding.
101+
102+
Let's look at an example. Imagine the following file `MathUtils.res`:
103+
104+
```rescript
105+
let add = (a, b) => a + b
106+
let sub = (a, b) => a - b
107+
```
108+
109+
Now let's dynamically import the add function in another module, e.g. `App.res`:
110+
111+
<CodeTab labels={["ReScript", "JS Output (ES6)"]}>
112+
```rescript
113+
// App.res
114+
let main = async () => {
115+
let add = await Js.import(MathUtils.add)
116+
let onePlusOne = add(1, 1)
117+
118+
Console.log(onePlusOne)
119+
}
120+
```
121+
```javascript
122+
async function main() {
123+
var add = await import("./MathUtils.mjs").then(function(m) {
124+
return m.add;
125+
});
126+
127+
var onePlusOne = add(1, 1);
128+
console.log(onePlusOne);
129+
}
130+
```
131+
</CodeTab>
132+
133+
### Dynamically Importing an Entire Module
134+
The syntax for importing a whole module looks a little different, since we are operating on the module syntax level; instead of using `Js.import`, you may simply `await` the module itself:
135+
<CodeTab labels={["ReScript", "JS Output (ES6)"]}>
136+
```rescript
137+
// App.res
138+
let main = async () => {
139+
module Utils = await MathUtils
140+
141+
let twoPlusTwo = Utils.add(2, 2)
142+
Console.log(twoPlusTwo)
143+
}
144+
```
145+
```javascript
146+
async function main() {
147+
var Utils = await import("./MathUtils.mjs");
148+
149+
var twoPlusTwo = Utils.add(2, 2);
150+
console.log(twoPlusTwo);
151+
}
152+
```
153+
</CodeTab>
154+
96155
## Export To JavaScript
97156

98157
### Export a Named Value

0 commit comments

Comments
 (0)