Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I serve remote React app with a script tag?

We have at our company a react app (built with create-react-app) which is served today via an iframe, which works well.

A need has risen to serve the app (which is always embedded within other pages), with a script tag alone (no iframe tag).

I thought of something like:

<div id="app-placeholder"></div>
<script src="https://our-app.com/init.js"></script> // this will create a function called window.InitMyApp
<script>
    InitMyApp('#app-placeholder', 'token', otherOptions)
</script>

I've tried to create init.js file in the react app's public folder. I can access the file. From that file, how can I render the react app itself to the given selector (#app-placeholder)?

Because this file is served as-is, and doesn't get transpiled by webpack/babel, I cannot use import/jsx/require() and other stuff.

Am i on the right track? Should I manually transpile this file? Are there any other solutions to this rendering method?

like image 563
Idan Ptichi Avatar asked Oct 17 '25 13:10

Idan Ptichi


1 Answers

You should try configuring the compiler with { output.library }. This should produce a compilation output that's ready for distribution, which means you can easily reference it in another document (and not need to worry about, say, transpiling/optimizing sources, because this was already performed by webpack).

Here's an example of a multi-part library produced by webpack. As you can see, the entrypoint exports are being assigned to window.

like image 134
Filip Dupanović Avatar answered Oct 19 '25 08:10

Filip Dupanović