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

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

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.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply