Rescript-compiler: Dynamic import support

Created on 2 Nov 2019  路  9Comments  路  Source: rescript-lang/rescript-compiler

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?

Most helpful comment

@bobzhang has there been progress on this? that'd be crucial for overall performance

All 9 comments

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

Was this page helpful?
0 / 5 - 0 ratings