I have an idea to use the same set of dependencies for remote components and the application’s own components. The scenario is as follows:
I have a main application A developed via vite+react , A is developed using regular modularization. Now I want to build a plugin repository R which holds some remote component comps. I want to load the comps from repository R in application A via dynamic import or other means. And render them for use in application A. Now there is a problem. Suppose component B in repository R is also developed using vite+react scaffolding and compiled and packaged using library mode.
The code for B looks like this:
import React, { PropsWithChildren } from 'react';
export type ButtonProps = {
className?: string;
};
const Button: React.FC<PropsWithChildren<ButtonProps>> = ({ className, ...props }) => {
return <button className={classNames('my-button', className)} {...props} onClick={()=>console.log('click')}/>;
};
export default Button;
During the packaging process you can configure to exclude the react dependency used by B development as follows:
rollupOptions: {
// 确保外部化处理那些你不想打包进库的依赖
external: ['react', 'react-dom'],
output: {
// 在 UMD 构建模式下为这些外部化的依赖提供一个全局变量
globals: {
react: 'react',
'react-dom': 'react-dom',
},
},
},
But for the packaged product of B, the first line may be compiled to import we from ‘react’;. Now B is placed on the server and loaded remotely by application A. B is executed immediately after loading (since B is a js file). The import statement cannot be parsed during execution. This results in an error. I would like to see that when A loads B, whether in development or production, they use the same copy of public dependencies such as react, is there a good solution?
I tried building B in vite packaged in library mode to exclude react dependencies and load the react dependencies of the A app at runtime, but this doesn’t seem to work after both A and B are compiled!