You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Module Federation在Safari中报错ReferenceError: Cannot access uninitialized variable的问题排查与解决求助

Module Federation在Safari中报错ReferenceError: Cannot access uninitialized variable的问题排查与解决求助

大家好,我最近遇到了一个Module Federation在Safari浏览器里的兼容性问题,想请教下有没有大佬遇到过或者有解决思路。

我的场景是这样的:我有多个React+Vite构建的应用,其中一个是作为宿主的App Shell,通过路由匹配来加载不同的远程联邦模块。我用的是@module-federation/runtime(也试过增强版的@module-federation/enhanced/runtime)里的loadRemote函数来实现远程模块的加载,相关代码如下:

远程模块加载钩子代码

import { loadRemote } from '@module-federation/runtime';
import { ComponentType, useState, useEffect} from 'react';
import { RemoteModule } from 'types/federation';

export function useRemoteModule(name: string): ComponentType<any> | null {
  const [module, setModule] = useState<ComponentType<any> | null>(null);

  useEffect(() => {
    const loadModule = async () => {
      try {
        const module = await loadRemote<RemoteModule>(`${name}/App`);
        if (!module?.default) {
          throw new Error(`Module ${name} does not have a default export`);
        }
        setModule(() => module.default);
      } catch (e) {
        console.log(e, 'catch');
      }
    }
    loadModule();
  }, [name])

  return module;
}

路由解析组件代码

export function RouteResolver({ routes }: RouteResolverProps) {
  const { '*': routeParams } = useParams();
  const configRoute = Object.keys(routes).find(
    (pathname: string) => matchPath(pathname, `/${routeParams}`)
  ) || '';
  const moduleName = getModuleName(routeParams, routes[configRoute]);
  const Module = useRemoteModule(moduleName || DEFAULT_MODULE);

  return (
    <Suspense>
      {Module ? <Module /> : null}
    </Suspense>
  );
}

问题表现是:在Chrome和Firefox里所有功能都正常,但在Safari浏览器中,绝大多数情况下会抛出以下错误导致页面崩溃,只有极少数时候能成功加载:

ReferenceError: Cannot access uninitialized variable. (anonymous function) — virtualExposes-Dh5dHcud.js:5

我还发现一个非常奇怪的现象:如果远程组件里用JSX语法(比如<div>Test</div>)就一定会触发这个错误,但如果改成用React.createElement('div', null, 'Test')来创建元素,就能正常渲染。

我已经尝试过以下几种方案,但都没有解决问题:

  • 编写自定义插件,将所有JSX语法自动转换为React.createElement调用
  • 切换使用@module-federation/runtime和@module-federation/enhanced/runtime两个包
  • 调整Module Federation的配置参数(比如修改暴露模块的方式、共享依赖的配置等)

想请教下各位,这个错误可能是什么原因导致的?有没有针对Safari浏览器的解决方案?

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.08 08:58:05