rescript-compiler
rescript-compiler copied to clipboard
Dynamic import support
type xx
type 'a promise
external import :
'a ->
('a -> unit) ->
unit promise = "bootload" [@@bs.val]
;;
module type LIST = module type of List
;;
let _ : _ promise =
import (module List : LIST)(fun (module List) ->
Js.log (List.length [1;2]);
()
)
Todo:
- Have a way to delay the generated requires for List
- See if we can mitigate the runtime cost
- Check to see how to ensure invariants enforced by bootload, e.g, it can only load a global module?
Is this regarding #2765 ?
@yawaramin yes, except the proposal here is more type safe?
@bobzhang your approach here made me think about this a bit more and now I think we can do dynamic imports with just bs.val
and bs.as
(treating import
as just a normal function), here's an example:
(* foo.ml *)
let x = 0
(* import.ml *)
module type FOO = sig
val x : int
end
external foo : (_ [@bs.as "./foo.bs"]) -> (module FOO) Js.Promise.t =
"import" [@@bs.val]
let _ = foo |> Js.Promise.then_(fun (module Foo : FOO) ->
Foo.x |> Js.log |> Js.Promise.resolve)
This generates:
// Generated by BUCKLESCRIPT, PLEASE EDIT WITH CARE
'use strict';
import("./foo.bs").then((function (Foo) {
return Promise.resolve((console.log(Foo.x), /* () */0));
}));
/* Not a pure module */
[EDIT: this is possible now thanks to the modules-as-objects change! On previous versions this would compile as Foo[/* x */ 0]
]
@bobzhang has there been progress on this? that'd be crucial for overall performance
@bobzhang any update? :-)
@yawaramin your solution works fine. Can we make it little more generic, so that it works for any module.
Something like below
module type DyImpConfig = {module type T;};
module Make = (Config: DyImpConfig) => {
[@bs.val] external importRe: string => Js.Promise.t(module Config.T) = "import";
};
@tejesh014 sure, that makes sense. I'll write up an article about it on my blog when I get some time.
I'm also interested in whether there has been any recent movement/plans here. 👀
Also looking to this
hey, any changes here?
#5703