mardi 4 juillet 2017

Build React app as modular JS library

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='http://ift.tt/2sDMk57' 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?




Aucun commentaire:

Enregistrer un commentaire