ReactJS 和 Webpack 模块联合应用程序在部署到 cloudfront 时包含未定义的 URL

问题描述

我有一个微前端应用程序,它由一个容器应用程序和多个远程应用程序组成。它使用带有 Webpack 5 模块联合的 ReactJS,并且在我的本地环境中运行良好。但是,当我将其部署到 AWS CloudFront 时,它无法按预期工作。

似乎容器应用加载到了正确的路径上,但“未定义”被添加到遥控器的 remoteEntry.js 文件的 url 中。

请看下面的截图:

CloudFront Error

容器项目webpack生产配置如下:

const prodConfig = {
  mode: "production",output: {
    filename: "[name].[contenthash].js",publicPath: "/container/latest/",},plugins: [
    new ModuleFederationPlugin({
      name: "container",remotes: {
        auth: `auth@${domain}/auth/latest/remoteEntry.js`,marketing: `marketing@${domain}/marketing/latest/remoteEntry.js`,dashboard: `dashboard@${domain}/dashboard/latest/remoteEntry.js`,shared: packageJson.dependencies,}),],};

远程项目webpack生产配置如下:

const prodConfig = {
  mode: "production",publicPath: "/marketing/latest/",plugins: [
    new ModuleFederationPlugin({
      name: "marketing",filename: "remoteEntry.js",exposes: {
        "./MarketingApp": "./src/bootstrap",};

容器项目App.js如下:

import React,{ lazy,Suspense,useState,useEffect } from "react";
import { Router,Route,Switch,Redirect } from "react-router-dom";
import {
  StylesProvider,createGenerateClassName,} from "@material-ui/core/styles";
import { createbrowserHistory } from "history";

import Progress from "./components/Progress";
import Header from "./components/Header";

const MarketingLazy = lazy(() => import("./components/MarketingApp"));
const AuthLazy = lazy(() => import("./components/AuthApp"));
const DashboardLazy = lazy(() => import("./components/DashboardApp"));

const generateClassName = createGenerateClassName({
  productionPrefix: "co",});

const history = createbrowserHistory();

export default () => {
  const [isSignedIn,setIsSignedIn] = useState(false);

  useEffect(() => {
    if (isSignedIn) {
      history.push("/dashboard");
    }
  },[isSignedIn]);

  return (
    <Router history={history}>
      <StylesProvider generateClassName={generateClassName}>
        <div>
          <Header
            onSignOut={() => setIsSignedIn(false)}
            isSignedIn={isSignedIn}
          />
          <Suspense fallback={<Progress />}>
            <Switch>
              <Route path="/auth">
                <AuthLazy onSignIn={() => setIsSignedIn(true)} />
              </Route>
              <Route path="/dashboard">
                {!isSignedIn && <Redirect to="/" />}
                <DashboardLazy />
              </Route>
              <Route path="/" component={MarketingLazy} />
            </Switch>
          </Suspense>
        </div>
      </StylesProvider>
    </Router>
  );
};

我正在努力找出错误所在。我不确定它是否是一个错误

  • 反应
  • 反应路由器
  • Webpack 模块联合
  • AWS CloudFront

任何帮助将不胜感激

解决方法

如果您仔细查看浏览器日志。

您的网址中有一个 undefined/marketing/latest/remoteEntry.js,用于加载模块联合远程网址。

您可能需要将 domain 变量设置为 Cloudfront 端点。