1

Background

I have a React app that was generated with create-react-app. It is a set of UI forms that are intended to be presented modally inside a hosting website. The hosting website provides a JS callback to be invoked upon completion.

Motivation

I want to be able to distribute this small React app as a standalone "vanilla" JS module, that can then embedded in any HTML page. What I have now is running npm run build and getting a full website with my app - but that's not what I need. A desirable output should be a simple .js file, that can be imported to a other's websites (that are not necessarily built with React). Braintree's JS SDK is a very good example of what I need.

Example usage in hosting website

<head>
    <!-- loading MyModule -->
    <script src='https://cdn.mydomain.com/mymodule.js' some-parameter='param-provided-by-hosting-website'></script>
</head>

<body>
    <div id="mymodule-container"></div>


    <!-- rest of hosting website... -->


    <script>
        // this will present a "full screen" UI component and call callback upon completion
        MyModule.presentUI(
            function callback() {
                console.log('MyModule completed');
            }
        );
    </script>
</body>

Putting aside all of the internal structure and consideration, how do I bundle my React app (including its .css files) as one .js file that runs inside another website?

UPDATE

So apparently running npm run build outputs, among other things, a static/main*****.js file, which is all of the JS contents. The index.html file is actually a good example of how to use that .js file as a module:

<!DOCTYPE html><html lang="en">
<head>
    <meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
    <link rel="shortcut icon" href="/favicon.ico">
    <title>My Hosting App</title>
    <link href="/static/css/main.1695e3be.css" rel="stylesheet">
</head>
<body>
    <div id="my-module-container"></div><script type="text/javascript" src="/static/js/main.0b4c7736.js"></script>
</body></html>

Now what's left to ask is how to load the .css (from built-generated static/main******.css file with the .js file, without making the hosting website also add a <link> tag to the RSS (like in the output index.html. Basically making this happen inside the generated .js file.

mllm
  • 17,068
  • 15
  • 53
  • 64

1 Answers1

1

I cannot say how this can be achieved without having some sort of 'standard' API, that all your modules can follow.

We have tried to do something similar with FrintJS (https://frint.js.org), with the concept of 'regions'.

You define certain areas where you want your Apps (modules according to your question) to mount themselves on, and they can be loaded asynchronously on demand via separate <script> tags.

You can read more here:

fahad19
  • 96
  • 2