I wonder if it is possible to import a couple of components from a remote source generated using @originjs/vite-plugin-federation components in my Vite React.js app.

Eg: I've an array of object as follows

export const components = [
  { name: "HRLandingDashBoard", path: "landingdashboard" },
  { name: "HRUpdateProfile", path: "updateprofile" },
  { name: "HRenrollmentList", path: "enrolementlist" },
  { name: "HRemployeExit", path: "employeeexit" },
  { name: "HRemployeExitApproval", path: "employeeexitapproval" },
  { name: "HRBulkEnrolement", path: "bulkenrolement" },
  { name: "HRBulkEnrolementExit", path: "bulkenrolementexit" },
  { name: "HRRevokeEmployeeExit", path: "revokeemployeeexit" },
  { name: "HREmployeeList", path: "employeelist" },
  { name: "HRUpdateProfileApproval", path: "updateprofileapproval" },
  { name: "HREmployeeExitReport", path: "employeeexitreport" }
];

I've tried importing them as below in my React.js App.tsx as follows

import { components } from "./module";
const componentImports: any = {};

components.forEach(({ name, path }) => {
  componentImports[name] = lazy(
    () => import(/* @vite-ignore */ `remoteHRApp/${path}`)
  );
});

and use it as

<Route
           path="hr-landingdashboard"
           element={
           <Suspense fallback={<div>Loading...</div>}>
               <componentImports.HRLandingDashBoard />
           </Suspense>}></Route>,

but this throws an error Uncaught TypeError: Failed to resolve module specifier 'remoteHRApp/landingdashboard' .

my vite config file looks like below

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react-swc";
import federation from "@originjs/vite-plugin-federation";
import dynamicImportVars from "@rollup/plugin-dynamic-import-vars";

// https://vitejs.dev/config/
export default defineConfig({
  base: "/",
  plugins: [
    react(),
    federation({
      name: "app",
      remotes: {
        remoteHRApp:
          "http://localhost:5051/hr-management/assets/remote-hr.js",
            },
      shared: ["react", "react-dom"],
    }),
    dynamicImportVars({
      include: ["src/**/*.tsx"],
      exclude: ["node_modules/**"],
      errorWhenNoFilesFound: true,
      warnOnError: true,
    }),
  ],
  build: {
    modulePreload: false,
    target: "esnext",
    minify: false,
    cssCodeSplit: false,
  },
});

Is there any workaround to make it working?

0

There are 0 best solutions below