I created a simple react component and I want to import it conditionally to another react app. I've managed to import it via HTML script tag and then get it from the window variable. The whole idea was working as long as react was being bundled in the module. I want to use the external react instance from the parent app, so I've configured webpack like this:
const path = require('path');
module.exports = {
entry: './index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'module.js',
library: 'test',
libraryTarget: 'umd',
},
externals: {
'react': {
'commonjs': 'react',
'commonjs2': 'react',
'amd': 'react',
'root': 'React'
}
}
};
edit:
I've changed the externals to { react: 'React' }
and in the parent app I've assigned the react to window.React
variable.
const Test = (window as any).test.default
console.log(window.React)
console.log(Test)
return <Test />
The code above results in the same error.
{Children: {…}, Fragment: Symbol(react.fragment), Profiler: Symbol(react.profiler), Component: ƒ, PureComponent: ƒ, …}
ƒ (){return o.default.createElement("p",{style:{color:"green",fontWeight:"bold"}},"Hello, I come from an external module!")}
module.js:1 Uncaught TypeError: Cannot read property 'createElement' of undefined
SOLVED!
I've found out that the React instance has to be available in the window.React
variable at the moment of loading UMD script. At first I've managed to get this to run by loading React from CDN before loading the script. Finally, I have decided to load the external component dynamically, after making sure window.React is available. It works as expected.