You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: pages/docs/manual/latest/import-from-export-to-js.mdx
+59Lines changed: 59 additions & 0 deletions
Original file line number
Diff line number
Diff line change
@@ -93,6 +93,65 @@ var studentName = Student;
93
93
94
94
</CodeTab>
95
95
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
+
<CodeTablabels={["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
+
asyncfunctionmain() {
123
+
var add =awaitimport("./MathUtils.mjs").then(function(m) {
124
+
returnm.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:
0 commit comments