How to dynamically import a file?

How to dynamically import a file?

I want to load json files only when needed instead of including them in the main bundle. In JS you would do import('./some-file.js') , but in RS I get an error:

  external import2: string => Js.Promise.t<array<string>> = "import"
  let z = import2("./some-file.js")
  // -> [ReScript 106] [W] Unimplemented primitive used:import

Hi, looks like you’re missing @val before your external definition.

@val external import2: string => Js.Promise.t<array<string>> = "import"
let z = import2("./some-file.js")

Will be compiled into:

var z = import("./some-file.js");
3 Likes

thanks Lomand, I would have never guessed that I missed @val from the error Unimplemented primitive used:import, this worked:

@val external import2: string => Js.Promise.t<{ "default": array<string> }> = "import"