Integrate Reactjs with JavaScript (React Microfrontend)
Render React App from JS by creating a API
Was recently tasked with a POC at work to integrate a Reactjs App in JavaScript
Learnings :
Create-React-App is not very flexible
Understanding Webpack and Babel gives you flexibility
A few quick brief definitions
Reactjs :- Framework to develop UI
Babel :- JavaScript transcompiler used to convert ECMAScript 2015+ code into a JavaScript that your browser understands.
Webpack :- A build time tool that bundles multiple JS files into one
Steps
Create React App from Scratch using Webpack and Babel.
Go to https://createapp.dev/ select the following configs and download.
Use this as your base project
Download Project with these configs
Configure Webpack to EXPORT REACT APP AS LIBRARY
Change the output of webpack.config.js
output : {
path : path.resolve(__dirname , 'build'),
filename: 'index.js',
library: 'react_withoutcra',
libraryTarget: 'commonjs2'
}
Expose a API in your React App as a ROOT component
export const notrender = (id:any,root:any)
We are done with the modifications to the React App
Run npm run build will create a bundle in build folder ready to be used by Legacy System.
run npm link that will make your library accessible locally
Modify the Legacy APP
Make sure the Parent App has webpack and Babel setup
Include the library created above via
npm install (if published) or
npm link <library name> if local
In any JS file you want to Render the React App import and call the API with the params
import react_withoutcra from 'react_withoutcra';
react_withoutcra.react_withoutcra.notrender(2221,'root2');
This is how you can render a React App from Pure JS via a API.
Will add a Github Link soon.