diff --git a/CHANGELOG.md b/CHANGELOG.md index 65ce313b..34a28a88 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,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 diff --git a/src/RescriptCore.res b/src/RescriptCore.res index 0cdb0025..e3ae6d11 100644 --- a/src/RescriptCore.res +++ b/src/RescriptCore.res @@ -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 diff --git a/test/ImportTests.mjs b/test/ImportTests.mjs new file mode 100644 index 00000000..6a94c12d --- /dev/null +++ b/test/ImportTests.mjs @@ -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 */ diff --git a/test/ImportTests.res b/test/ImportTests.res new file mode 100644 index 00000000..961e3ff1 --- /dev/null +++ b/test/ImportTests.res @@ -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