Load React16 Build Into another app with RequireJS - reactjs

I built a small React application that ultimately will be in a section on a page with other small apps. The way the system is architected requires that each app be a require module that exports an init function that when called will render the app into a div by id. I have already tweaked my React build so that I have a single js file. Now I'm trying to figure out if I can make this final build be somehow loadable with requirejs. I have found a lot of information about using requirejs as part of the build but I would rather be able to stay with the create-react-app way and maybe somehow add in the ability to do the output in an AMD way. I know this must seem silly but I can't otherwise get around the AMD architecture of this platform.

You can achieve this by tweaking the configuration of webpack.config.js file, you need to check out webpack's output.library options (library, libraryExport, and libraryTarget):
https://webpack.js.org/configuration/output#module-definition-systems
module.exports = {
//...
output: {
library: 'MyReactAppLibrary',
libraryTarget: 'amd'
}
}

Related

Using components from an external directory in a Electron project with Webpack

I am trying to do this as simple as possible, I studied Yarn Workspaces for a while, but that's a solution that's currently doesn't work with Electron, there were simply too many issues.
I have am Electron project here: ./electron/
I have a directory with components here: ./common/
The components are developed in React/JSX, there is nothing really fancy about them. That said, I am using hooks (useXXX).
I tried many ways to include those components (ideally, I wanted to use Yarn Workspaces, but it only multiplied the number of issues), but they all failed. Which is why I would like to avoid using yarn link or workspaces or making the common a library, etc. I just want my Electron project to behave as if the files were under ./electron. That's it.
The closest I came to a solution is by using electron-webpack, and overriding it with this config:
module.exports = function(config) {
config = merge.smart(config, {
module: {
rules: [
{
test: /\.jsx?$/,
//include: /node_modules/,
include: Path.resolve(__dirname, '../common'),
loaders: ['react-hot-loader/webpack', 'babel-loader?presets[]=#babel/preset-react']
},
]
},
resolve: {
alias: {
'#common': Path.resolve(__dirname, '../common')
}
}
})
return config
}
I can import modules, and they work... except if I use hooks. And I am getting the "Invalid Hook Call Warning": https://reactjs.org/warnings/invalid-hook-call-warning.html.
I feel like that /common folder is not being compiled properly by babel, but the reality is that I have no idea where to look or what to try. I guess there is a solution for this, through that webpack config.
Thanks in advance for your help :)
I found the solution. That happens because the instance of React is different between /common and /electron.
The idea is to add an alias, like this:
'react': Path.resolve('./node_modules/react')
Of course, the same can be done for other modules which need to be exactly on the same instance. Don't hesitate to comment this if this answer it not perfectly right.
I wrestled more than a day with a similar problem. My project has a dependency on a module A that is itself bundled by Webpack (one that I authored myself). I externalised React from A (declaring it to be a commonjs2 module). This will exclude the React files from the library bundle.
My main program, running in the Electron Renderer process, uses React as well. I had Webpack include React into the bundle (no special configuration).
However, this produced the 'hooks' problem because of two instances of React in the runtime environment.
This is caused by these facts:
module A 'requires' React and this is resolved by the module system of Electron. So Electron takes React from node_modules;
the main program relies on the Webpack runtime to 'load' React from the bundle itself.
both Electron and the Webpack runtime have their own module cache...
My solution was to externalise React from the main program as well. This way, both the main program and module A get their React from Electron - a single instance in memory.
I tried any number of aliases, but that does not solve the problem as an alias only gives direction to the question of where to find the module code. It does nothing with respect to the problem of multiple module caches!
If you run into this problem with a module that you cannot control, find out if and how React is externalised. If it is not externalised, I think you cannot solve this problem in the context of Electron. If it is externalised as a global, put React into your .html file and make your main program depend on that as well.

How can I debug a React JS App into Cordova?

I was trying to integrate a React.js app in Cordova. Everything goes well, but I was not able to debug the app in the simulator. With chrome://inspect it seems like there's no way to do it, because I can only see the "compiled code". Any solution? Thanks
Maybe there is another better way, but what do the trick for me is to build react with some custom files that i took from node_modules/react-scripts/
(i do that, to avoid react eject)
You need all the sources map on your app.
React by default, use a certain webpack config, but that config doesn't work in your phone.
By default, react use this
You can check it on the file node_modules/react-scripts/config/webpack.config.js
What i do, is to build react with the next webpack config
devtool: "eval-source-map",
So you must
Copy these files on your source code and adapt some imports (there are some import with relative path) You only need these two files
node_modules/react-scripts/scripts/build.js
node_modules/react-scripts/config/webpack.config.js
On the first one, modify it to use the second one,
On the second one, add this devtool: "eval-source-map"
Create new task on package.json , new custom build to use the script your custom build.js
Build with this script, and copy all the source maps with your code, and thats it.
The debug could crash sometimes, (i try it also with iphone + safari, sometimes works, sometimes don't so you must keep trying)
On android tend to work in a better way.
The debug is a little bit slow in compare to the web debug.
I hope this works for you too.
(Sorry for my bad English)

How to create a Micro Frontend bundle with Webpack that shares libraries with the container application?

I have a task.
To have Micro Frontends with single-spa framework.
portal/main application (which load all other js code by url)
Micro Frontend 1 (react based)
Micro Frontend 2 (react based)
So my problem just one: I don't want to duplicate vendor libraries like react, react-dom (any others). And I want to make them shared among other Micro Frontends (which is bundled with webpack)
I know what is the bad practice to have some global stuff (it's violate the whole idea of bundeling with webpack). But how to solve the problem of duplication of vendor libraries?
I found one solution just load decencies with SystemJs like separated tags in html, but I just wonder maybe there is another solutuion for that.
Thank you.
SystemJs approach to load dependencies by demand but from CDN, I just want do the same but load all dependencies from "shared" webpack bundle with react and other stuff.
window.SystemJS = window.System
function insertNewImportMap(newMapJSON) {
const newScript = document.createElement('script')
newScript.type = 'systemjs-importmap'
newScript.text = JSON.stringify(newMapJSON)
const allMaps = document.querySelectorAll('script[type="systemjs-importmap"]')
allMaps[allMaps.length - 1].insertAdjacentElement(
'afterEnd',
newScript
)
}
const devDependencies = {
imports: {
react: 'https://cdnjs.cloudflare.com/ajax/libs/react/16.8.6/umd/react.development.js',
'react-dom': 'https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.development.js',
'react-dom/server': 'https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom-server.browser.development.js',
'single-spa': 'https://unpkg.com/single-spa#4.3.2/lib/umd/single-spa.min.js',
lodash: 'https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js',
rxjs: 'https://unpkg.com/rxjs#6.4.0/bundles/rxjs.umd.js',
}
}
const prodDependencies = {
imports: {
react: 'https://cdnjs.cloudflare.com/ajax/libs/react/16.8.6/umd/react.production.min.js',
'react-dom': 'https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.production.min.js',
'react-dom/server': 'https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom-server.browser.production.min.js',
'single-spa': 'https://unpkg.com/single-spa#4.3.2/lib/umd/single-spa.min.js',
lodash: 'https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js',
rxjs: 'https://unpkg.com/rxjs#6.4.0/bundles/rxjs.umd.min.js',
}
}
const devMode = true // you will need to figure out a way to use a set of production dependencies instead
if (devMode) {
insertNewImportMap(devDependencies)
} else {
insertNewImportMap(prodDependencies)
}
Update:
Just realized, that your question is directed at Micro Frontends (not only micro services) and therefore is not about sharing libraries with Webpack in general. Added Micro Frontend to your tags/title and updated the answer to be more focused on this topic.
So my problem just one: I don't want to duplicate vendor libraries like react, react-dom (any others). And I want to make them shared among other [Micro Frontends] (which is bundled with webpack)
What you can do is exclude dependencies from the output bundle of your Micro Frontends by adding a Webpack externals property to the config.
webpack config of your Micro Frontends:
module.exports = {
...
externals = {
react: 'React',
'react-dom': 'ReactDOM'
}
}
Above config would exclude react and react-dom and expect them in the global variables React and ReactDOM. You can then share those dependencies by including the libraries in a script inside index.html of your root applicationn aka stitching layer:
<html>
...
<body>
...
<script src="<your-host>/react.prod-16.9.0.min.js"></script>
<script src="<your-host>/react-dom.prod-16.9.0.min.js"></script>
</body>
</html>
If you have other common components to share, you can also integrate the library scripts in a component library.
The reason for the include as script is: We do not want that our container has to require/import the Micro Frontends at build time in order to avoid a coupling of build/release/version management between all apps. Instead one purpose of Micro Frontends is to achieve fully independent deployment of the parts, which include continuous delivery steps from build, test to release.
I know what is the bad practice to have some global stuff (it's violate the whole idea of bundeling with webpack).
Of course, you create some form of coupling between the apps. But if you have a mature, stable and common library shared by all parts, it is a reasonable decision.
Hope, it helps (now)!
The best way to achieve this today is using Webpack's new Module Federation technology released in v5. This approach does not use SystemJS but rather the internals of Webpack. We tried several different micro frontend approaches, but this one outshines them all & is currently running successfully for us in production. There are definitely some challenges to setting it up but it was worth the developer productivity gains.
Here is the info site produced by the creator Zack Jackson which should provide all the resources you need: https://module-federation.github.io/
Here is the link to webpack docs which deal more with technicalities rather than how to practically set up a full micro frontend architecture: https://webpack.js.org/concepts/module-federation/

Webpack: How can I combine two completely separate bundles using dynamic bundling

I have spent a lot of time looking into this, but to no avail. I am aware of how code splitting and dynamic bundling works in Webpack using the import promise API.
Howevr, my use case is that I have two completely separate bundles, generated separately using different webpack builds. To give you perspective, I am building React components and there is a requirement to dynamically load a react component into the page that has been compiled in a different process. Is this possible in react? I do have control over both webpack builds, so I can exclude dependencies, etc.
Update: I just looked at Vue.js, and how it allows developers to register Vue.js components and then reference them later in the code. I could potentially load my Vue.js component scripts before my page script. I'm trying to see if I can do something similar in React.
Did I understand you correctly: you have essentially got
a library of custom React components (built by Webpack build #1)
a React app that needs to use some (all) of these components (built by Webpack build #2, totally separate from #1)
?
If yes, then read on.
The "Is this possible in react?" question should instead be "Is this possible in Webpack?", and the answer is "Yes". The following is tested with Webpack 2, but should also work with v.1.
Let's call your projects Lib (your React component library) and App (the library consumer).
In the Lib project:
Create an entry point file, say index.js, that exports all the custom React components like this:
import {Button} from './button';
import {DatePicker} from './DatePicker';
import {TextBox} from './textBox';
export const MyComponentLib = {
Button,
DatePicker,
TextBox
};
Update webpack.config.js to make the project's bundle a UMD library (could also be 'var'), and set the entry point to the above index.js file. Doing so will make your library available via a global variable named MyComponentLib (the name comes from the export above) in the consuming app later on:
...
output: {
path: './dist',
filename: 'mylib.bundle.js',
libraryTarget: 'umd'
},
...
entry: './index.js',
...
On to the App project:
In the index.html file you will have two <script> tags: one for mylib.bundle.js (the output of the Lib project), and another for the bundle of the App project itself. You might have more bundles (app, vendor etc.), I'm just simplifying things here.
Update webpack.config.js to mark the component library as external dependency. Here, MyComponentLib is, again, the name of the global variable the library is available at, and myComponents is the name to use in import statements:
...
externals: {
myComponents: 'MyComponentLib'
},
...
Now, in App you can import a component like this:
import {DatePicker} from 'myComponents';
This will dynamically load DatePicker from the component library at run time via the global variable.
Bonus: if you use eslint, you don't want it to complain about missing modules that you know are external; add this to your .eslintrc:
...
"settings": {
"import/core-modules": ["myComponents"]
},
...

React with Webpack - package a module for use in Dynamic loading in another site

I'm using Webpack as our build/bundler for an application using a standard React/Redux/etc.
We have a requirement to build out custom components that can be loaded dynamically into the main application. This would require that the component is created OUTSIDE the main development so would not be involved in the main app build. The ideal solution would be to build out the components in their own side projects, bundle up (since they will have imports/require, etc) and spit out a bundle.js file that is only that component (could be multiple components merged together). Then we'd like to be able to take that file and dynamically load it in the main application dynamically.
I understand how code splitting works with webpack to a certain degree which we use in our main project. I've also been able to successfully import SIMPLE components externally I built out externally. The problem is that these external components can get pretty hefty so using a build/bundler to put it all together in one package would be ideal. I have no idea how to go about building components externally from the main project, bundle up using webpack to merge in all of the goodies into one package and inject that new bundled component which is typically wrapped in webpackjsonp and all the other runtime stuff.
Has anybody else been able to do something crazy like this?
Thanks!
EDIT
I've been able to successfully build a silo component in it's own project using webpack and dynamically loading that into a different running application bundled with webpack by using the Output.Library options as described here
Below is the sample config I used for testing a custom react component called TestMe located inside the index.js file of the test folder.
module.exports = {
entry: {
developer: "./test"
},
output: {
path: path.join(__dirname, "dist", "static", "developer"),
filename: "MyLibrary.[name].js",
library: ["MyLibrary", "[name]"],
libraryTarget: "var"
},
externals: {
'react': 'React'
, 'react-dom': 'ReactDOM'
, 'react-dom/server': 'ReactDOMServer'
, 'react/lisb/ReactTransitionGroup': 'React.addons.TransitionGroup'
, 'react/lib/ReactCSSTransitionGroup': 'React.addons.CSSTransitionGroup'
}, ...
When imported in you will have access to the TestMe component as a global variable MyLibrary.developer.TestMe (or MyLibrary.developer.default depending on how you exported the component). The externals are there to keep Webpack from including those in the final bundle which was already included in the main application. Otherwise you're going to get a really big nasty bundle file. Check out LibraryTarget if you rather have UMD, etc.
Moral of the story here is "when all else fails, read the docs again".

Resources