Skip to content

Commit

Permalink
Add Dynamic import (rescript-lang#178)
Browse files Browse the repository at this point in the history
* upgrade rescript to v11

* format files

* add import

* update tests

* update CHANGELOG.md
  • Loading branch information
aspeddro authored Feb 23, 2024
1 parent 5e9abe4 commit 2c5d7e2
Show file tree
Hide file tree
Showing 4 changed files with 69 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
- Add `Dict.forEach`, `Dict.forEachWithKey` and `Dict.mapValues` https://github.com/rescript-association/rescript-core/pull/181
- Remove internal xxxU helper functions that are not needed anymore in uncurried mode. https://github.com/rescript-association/rescript-core/pull/191
- Rename `Object.empty` to `Object.make` for consistency.
- Add dynamic `import`. https://github.com/rescript-association/rescript-core/pull/178

## 1.0.0

Expand Down
37 changes: 37 additions & 0 deletions src/RescriptCore.res
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,43 @@ external null: Core__Nullable.t<'a> = "#null"
external undefined: Core__Nullable.t<'a> = "#undefined"
external typeof: 'a => Core__Type.t = "#typeof"

/**
`import(value)` dynamically import a value or function from a ReScript
module. The import call will return a `promise`, resolving to the dynamically loaded
value.
## Examples
`MathUtils.res` file:
```rescript
let add = (a, b) => a + b
let sub = (a, b) => a - b
```
In other file you can import the `add` value defined in `MathUtils.res`
```rescript
let main = async () => {
let add = await import(MathUtils.add)
let onePlusOne = add(1, 1)
Console.log(onePlusOne)
}
```
Compiles to:
```javascript
async function main() {
var add = await import("./MathUtils.mjs").then(function(m) {
return m.add;
});
var onePlusOne = add(1, 1);
console.log(onePlusOne);
}
```
*/
external import: 'a => promise<'a> = "#import"

type t<'a> = Js.t<'a>
module MapperRt = Js.MapperRt
module Internal = Js.Internal
Expand Down
23 changes: 23 additions & 0 deletions test/ImportTests.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Generated by ReScript, PLEASE EDIT WITH CARE

import * as Test from "./Test.mjs";

async function main() {
var eq = await import("./IntTests.mjs").then(function (m) {
return m.eq;
});
return Test.run([
[
"ImportTests.res",
5,
22,
55
],
"dynamic import - Int tests - eq"
], 1, eq, 1);
}

export {
main ,
}
/* Test Not a pure module */
8 changes: 8 additions & 0 deletions test/ImportTests.res
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
open RescriptCore

let main = async () => {
let eq = await import(IntTests.eq)
Test.run(__POS_OF__("dynamic import - Int tests - eq"), 1, eq, 1)
}

main->ignore

0 comments on commit 2c5d7e2

Please sign in to comment.