I have a main react app in which based on a selected service, I'm dynamically loading another react app to a second root. The second app I'm loading is bundled using the webpack.config below...
const path = require("path")
const UglifyJsPlugin = require("uglifyjs-webpack-plugin")
const glob = require("glob")
module.exports = {
entry: {
"bundle.js": glob.sync("build/static/?(js|css)/*.?(js|css)").map(f => path.resolve(__dirname, f)),
},
output: {
filename: "build/bundle.min.js"
},
module: {
rules: [
{
test: /\.css$/,
use: ["style-loader", "css-loader"],
},
],
},
plugins: [new UglifyJsPlugin()],
}
This is then called in the build process via the modified npm run build command in my package.json below.
"build": "npm run build-sass npm run build:react && npm run build:bundle",
"build:react": "react-scripts build",
"build:bundle": "webpack --config webpack.config.js",
"build-sass": "node-sass --precision=5 --indent-type=space --output-style=nested --indent-width=2 src/styles/Site.scss src/styles/Site.css",
There were several issues with this approach which I discovered is down to react-scripts jsonpFunction in articles Hosting multiple React applications on the same document and How to run multiple webpack instances on the same page…and avoid any conflicts .
Following their advice the best I can I've tried adding arguments to the build command like below
"build:react": "react-scripts build --jsonpFunction=othername"
and
"build:react": "react-scripts build --output jsonpFunction=othername"
and other ways that don't fail build but the only way I've managed to get it to actually work in any way whatsoever was to go into react-scripts and modify the webpack config directly.
Due to the nature of what I need these other projects to do I cannot eject the projects and need to stick with react-scripts, so does anyone know a way of overriding this setting in react-script's webpack.config?
EDIT: I found a pending pull request potentially solving this issue on modification but it seems to be at a standstill, a workaround would be nice
Found the closest thing to an answer available at the moment. In the latest version of react-scripts (3.1.1 at the time of writing) the build process uses the name parameter in the package.json to make the jsonpFunction unique (assuming you're not loading projects with the same name).
The only downside is that in this change the bundling process does not put the function on the window, rather "this". So while the main app is bootstrapping the application with the jsonpFunction on window I need to do a find and replace on the bundled output to find this["webpackJsonp{projectName}"]
and replace it with window.webpackJsonp{projectName}
.
A perfectly viable (if not slightly grubby) workaround.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With