Search code examples
reactjsreasonbucklescriptreason-reactrescript

Can I make Reason+React import react module from CDN?


Building a component with Reason and React always gives me an module import statement for "react", which cannot be found if React is included from a CDN. Is there a solution for this? I've tried to define window.react = React in index.html without success. es6-global setting does not change anything.

I'm not using a bundling program like webpack.

Edit: Possibly relevant thread from Reason forum: https://reasonml.chat/t/can-one-load-reasonml-es6-modules-without-a-bundler/2219

Similar issue (not resolved): can one load reasonml es6 modules without a bundler

importmap (not yet implemented in browsers) could be another solution for this: Using ES6 Modules without a Transpiler/Bundler step


Solution

  • Technically, yes you can, but it's not going to be as easy as going with the npm flow and using a bundler.

    The ReasonReact bindings are written in a way that produces output JavaScript that imports modules like:

    import * as React from "react";
    

    (If using ES6 module style.)

    If using a CDN you would probably want an output that looks like this:

    import * as React from "https://some.cdn/react";
    

    The syntax (from the ReasonReact repo) that controls the output JS is:

    [@bs.module "react"]
    external createElement: (component('props), 'props) => element = "createElement";
    

    If you changed it to:

    [@bs.module "https://some.cdn/react"]
    external createElement: (component('props), 'props) => element = "createElement";
    

    ...then you'd get the desired output. But the problem is then you need to change the sources ... i.e. maintain or find forked bindings for React for that CDN. Or set up some code automation that does a find-and-replace of [@bs.module "react"] with [@bs.module "https://some.cnd/react"]. So either way, it's not as simple as using a bundler.