vite-plugin-federation

repository·main·Indexed 25 days ago

https://github.com/originjs/vite-plugin-federation

A Vite and Rollup plugin that enables Module Federation, allowing developers to share code between different projects (Host and Remote) with compatibility for Webpack. It supports exposing modules via the 'exposes' configuration and consuming them via the 'remotes' configuration, with examples provided for React, Vue 2, and Vue 3.

Tokens
10.9K
Snippets
37
Records
57
Agent score
84%

What's inside vite-plugin-federation

  1. Integration with Webpack

    main

    The plugin is compatible with Webpack Module Federation. You can use components exposed by vite-plugin-federation in a Webpack project, or use components exposed by Webpack's ModuleFederationPlugin in a Vite project.

    Important Notes:

    1. When using Webpack to consume Vite-exposed components, it is recommended to use the esm format as other formats lack complete test coverage.
    2. For React projects, mixing Vite/Rollup and Webpack is discouraged because inconsistent commonjs chunk generation can cause issues with shared dependencies.
    3. When using different bundling frameworks, you may need to specify remotes.from and remotes.format properties for better compatibility.
  2. Dynamically add remotes using `virtual:__federation__`

    main

    If you cannot define remote applications in advance in vite.config (e.g., they need to be loaded asynchronously from a backend), use the virtual:__federation__ module to implement dynamic loading at runtime.

    import {
      __federation_method_getRemote as getRemote,
      __federation_method_setRemote as setRemote,
      __federation_method_unwrapDefault as unwrapModule,
      type IRemoteConfig,
    } from "virtual:__federation__";
    
    const loadCrmPlugins = async () => {
      try {
        const pluginsResponse = await fetch("some-backed.com/plugins");
        const pluginsJson = await pluginsResponse.json();
        
        const unresolvedPlugins = pluginsJson.map(async (plugin) => {
          // 1. Register the remote
          setRemote(plugin.name, {
            ...commonRemoteConfig,
            url: plugin.entry,
          });
    
          // 2. Retrieve the component
          const remoteModule = await getRemote(plugin.name, plugin.component);
          
          // 3. Unwrap the default export
          const remoteComponent = await unwrapModule(remoteModule);
          
          renderComponent(plugin.name, remoteComponent);
        });
    
        await Promise.all(unresolvedPlugins);
      } catch (e) {
        console.error(e);
      }
    };
  3. Run the VueJs Module Federation with Style Demo

    main

    To run the demo project located in packages/examples/vue3-demo-esm/css-modules, follow these steps using pnpm:

    1. Install dependencies: Run pnpm install in the project folder.
    2. Build the project: Run pnpm build. This builds the following components:
      • common-lib (Port 5002)
      • home (Port 5001)
      • css-modules (Port 5002)
      • layout (Port 5000)
    3. Serve the project: Run pnpm serve to start the local servers.

    Access URLs:

    pnpm install
    pnpm build
    pnpm serve
  4. Run the Vue2 Module Federation Demo

    main

    To run the Vue2 Module Federation demonstration, which shows a host-simple application consuming a component from a remote-simple application, follow these steps:

    1. Navigate to the example directory: cd packages/examples/vue2-demo
    2. Install dependencies: pnpm install
    3. Build the projects: pnpm build
    4. Start the services: pnpm serve

    This will build and serve both applications on the following ports:

    To stop all services, run pnpm stop. Note that using CTRL + C may only stop the host server.

    cd packages/examples/vue2-demo
    pnpm install
    pnpm build
    pnpm serve
    
    # To stop all services
    pnpm stop
  5. Manually Handle Styles with dontAppendStylesToHead

    main

    If you set dontAppendStylesToHead: true in your exposes configuration, you must manually inject the styles into your component (e.g., inside a ShadowDOM). The plugin attaches an array of CSS file paths to the window object using the key css__{app_name}__{exposed_key}.

    const styleContainer = document.createElement("div");
    const hrefs = window["css__App__./remote-simple-button"];
    
    hrefs.forEach((href: string) => {
        const link = document.createElement('link')
        link.href = href
        link.rel = 'stylesheet'
        styleContainer.appendChild(link);
    });
  6. Run the Basic Rollup Module Federation Demo

    main

    To run the demonstration of Module Federation using Rollup, you must first prepare the monorepo root and then execute the specific example commands. This demo runs both a host (on port 5000) and a remote (on port 5001).

    1. Prepare the monorepo root:

      • Clone the originjs/vite-plugin-federation repository.
      • Run pnpm install at the root to install dependencies.
      • Run pnpm build at the root to build the workspace.
    2. Run the example:

      • Navigate to the example directory: cd packages/examples/basic-host-remote
      • Run pnpm install, pnpm build, and pnpm serve.

    Access URLs:

    Stopping the services:

    • CTRL + C only stops the host server.
    • To stop all running services, use pnpm stop.
    # At repository root
    pnpm install
    pnpm build
    
    # In packages/examples/basic-host-remote
    cd packages/examples/basic-host-remote
    pnpm install
    pnpm build
    pnpm serve
    
    # To stop all services
    pnpm stop
  7. Run the Vue3 Advanced Module Federation Demo

    main

    To run the full suite of services (Host and multiple Remotes) for the Vue3 Advanced Demo, navigate to the example directory and use the pnpm restart command. This will compile and start the services on ports 5001, 5002, and 5003.

    Note: CTRL + C only stops the host server. To stop all running services, use pnpm stop.

    cd packages/examples/vue3-advanced-demo
    pnpm restart
  8. Run the React - Vite Federation Demo

    main

    This demo showcases how a React-based host application consumes federated modules from a React-based remote application bundled with Vite.

    To run the demo locally:

    1. Ensure pnpm is installed.
    2. Install dependencies: pnpm install.
    3. Build and serve both applications: pnpm run build and pnpm run serve.

    Upon running, the applications will be available at:

    Note: CTRL + C only stops the host server. To stop all services, use pnpm stop.

    pnpm install
    pnpm run build
    pnpm run serve
    
    # To stop all services
    pnpm stop
  9. Static vs Dynamic Imports

    main

    The plugin supports both static and dynamic imports for remote modules.

    Vue Examples:

    Dynamic Import:

    const myButton = defineAsyncComponent(() => import('remote/myButton'));
    app.component('my-button' , myButton);
    // or
    export default {
      name: 'App',
      components: {
        myButton: () => import('remote/myButton'),
      }
    }

    Static Import:

    import myButton from 'remote/myButton';
    app.component('my-button' , myButton);
    // or
    export default {
      name: 'App',
      components: {
        myButton: myButton
      }
    }

    React Examples:

    Dynamic Import:

    const myButton = React.lazy(() => import('remote/myButton'))

    Static Import:

    import myButton from 'remote/myButton'

    Warning: Static imports may require browser support for Top-level await. You should set build.target to next in your Vite config or use the vite-plugin-top-level-await plugin.

  10. Run the Webpack host and Vite remote demo

    main

    This demo showcases how to consume federated modules from a Vite bundle (remote) within a Webpack host.

    To run the full demo environment, use the following commands:

    1. Install dependencies: pnpm install
    2. Build and serve both host and remote: pnpm run build and pnpm run serve

    Once running, the services are available at:

    Note: CTRL + C only stops the host server. To stop all services, run pnpm stop.

    pnpm install
    pnpm run build
    pnpm run serve
    
    # To stop all services
    pnpm stop
  11. Run the React - Module Federation Demo

    main

    To run the simple-react-esm example, which demonstrates consuming federated modules from a Rollup bundle where a remote app depends on a component exposed by a host app, follow these steps:

    1. Navigate to the example directory:
      cd packages/examples/simple-react-esm
    2. Build and serve the applications:
      pnpm build
      pnpm serve

    After running these commands, the services will be available at:

    Note on stopping services:

    • CTRL + C only stops the host server.
    • To stop all services, run:
      pnpm stop
    cd packages/examples/simple-react-esm
    pnpm build
    pnpm serve