I have two projects, Project A and Project B. Project A contains a React component, and I want to inject this component into Project B by creating a bundle of the component. I’ve tried various Vite configurations.
In Project B, I’m importing the bundle file using the use-script-hook (which basically injects the bundle into the window). While I’m able to inject it into the window, there are several errors indicating multiple versions of React in the project. I’ve ensured that the bundle does not include React dependencies.
Interestingly, when I comment out the index.js code that renders the React project and directly injects React and React-DOM through CDNs using script tags in index.html (while also injecting the bundle with the script tag), I’m able to mount the component in Project B.
Is there any other way to add the component as part of Project B without encountering these issues? Any help would be appreciated.
I tried with this vite-config :
import path from 'path';
import react from '@vitejs/plugin-react';
import { defineConfig, loadEnv } from 'vite';
import process from 'process';
import cssInjectedByJsPlugin from 'vite-plugin-css-injected-by-js';
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), '');
return {
define: {
'process.env': env,
},
plugins: [react(), cssInjectedByJsPlugin()],
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
},
},
build: {
lib: {
entry: path.resolve(__dirname, 'src/index.ts'),
name: 'MyComponent',
fileName: (format) => `MyComponent.${format}.js`,
formats: ['es', 'umd'],
},
rollupOptions: {
external: ['react', 'react-dom', 'react-dom/client'],
output: {
globals: {
react: 'React',
'react-dom': 'ReactDOM',
'react-dom/client': 'ReactDOMClient',
},
},
},
},
};
});
Dixit Tilaji is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.