2

I am using webpack and babel for building my app and app is building successfully in file bundle.js.

I have index.jsx file that has this code

import React from 'react';
import { render } from 'react-dom';
import App from './App';

render(<App />, document.getElementById('app'));

App component has bunch of other components loading up.

I have index.html file in the same app.

<html>
  <head>
    <meta charset="utf-8">
    <title>My App</title>
  </head>
  <body>
    <div id="app" />
    <script src="public/bundle.js" type="text/javascript"></script>
  </body>
</html>

I am opening index.html file from system directory, directly in browser and app is running fine.

What I want to do is to use bundle.js file and load my script in another html/javascript application, that run same application inside it.

I have found this Writing embeddable Javascript plugin with React & Webpack link that shows how he managed to use it.

Where he uses

export const init = (config) => {
  ReactDOM.render(<MyReactApp config={config} />, someSelector);
}

How can I convert my index.jsx file so that can be used in another app, same way it is being used in answer of link given.

Umair Jameel
  • 1,573
  • 3
  • 29
  • 54
  • Use a UMD library: http://bob.yexley.net/umd-javascript-that-runs-anywhere/ and https://webpack.js.org/configuration/output/ – Jonathan Rys May 10 '18 at 14:48
  • I have added it in webpack.config.js file as output: { path: BUILD_DIR, filename: 'bundle.js', library: 'MyApp', libraryTarget: 'umd', umdNamedDefine: true, }, – Umair Jameel May 10 '18 at 14:49

1 Answers1

1

Like he says in the other answer

<script src="./bundle.js" type="text/javascript"></script>
<script type="text/javascript">
  MyApp.yourExportedFunction();
</script>

But that's just for using an exported function. It looks like you want to have your entire app render in a different index.html file in some other app, so in your index.html of the other app you would need:

<div id="app"></div>

and

<script src=".path/to/other/project/bundle.js" type="text/javascript"></script>

then the app will render inside your div#app tag because that's what your library does:

render(<App />, document.getElementById('app'));
Jonathan Rys
  • 1,782
  • 1
  • 13
  • 25
  • Its working, but I shared link because I wanted to modify my index.jsx or html file to receive some parameters, send from where I want to use. just like in link – Umair Jameel May 10 '18 at 15:18
  • Then you would have to export the function that does the rendering like he did and pass your parameters to the function as shown in his example. – Jonathan Rys May 10 '18 at 15:23