跳转到内容
View in the app

A better way to browse. Learn more.

彼岸论坛

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.
欢迎抵达彼岸 彼岸花开 此处谁在 -彼岸论坛

[问与答] vite 构建的产物如何实现远程模块与本地应用模块使用同一份依赖?比如 react

发表于

我有一个想法,将远程组件和应用自身的组件使用同一套依赖。 场景如下:

我有一个通过 vite+react 开发的主应用 A ,A 使用常规的模块化开发。 现在我想搭建一个插件仓库 R ,R 中存放一些远程组件 comps 。 在应用 A 中通过动态 import 或者其他方式加载仓库 R 中的 comps 。并在应用 A 中渲染使用。 现在有一个问题。 假设仓库 R 中的组件 B ,也是使用 vite+react 脚手架开发的,使用库模式编译打包。

B 代码如下:


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;

在打包的过程中可以配置排除 B 开发时使用的 react 依赖,配置如下:

rollupOptions: {
     // 确保外部化处理那些你不想打包进库的依赖
     external: ['react', 'react-dom'],
     output: {
       // 在 UMD 构建模式下为这些外部化的依赖提供一个全局变量
       globals: {
         react: 'react',
         'react-dom': 'react-dom',
       },
     },
   },

但是对于 B 打包后的产物来说,他的第一行可能被编译为了 import we from 'react';的状态。 现在 B 被放在服务器上使用应用 A 进行远程加载。 加载 B 后会立即执行 B(由于 B 是 js 文件)。此时执行的过程中无法解析这个 import 语句。 导致出现了错误。 我希望不管是在开发阶段还是生产阶段,A 加载 B 时,像 react 这样的公共依赖,他们都能使用同一份,有什么好的解决方案嘛?

Featured Replies

No posts to show

创建帐户或登录来提出意见

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.