Vite: Module Federation with Vue3

Create two projects called vite-remote and vite-host:

npm create vite@latest vite-remote -- --template vue
npm create vite@latest vite-host -- --template vue

Install the plugin in both apps:

npm install @originjs/vite-plugin-federation --save-dev
# or
yarn add @originjs/vite-plugin-federation --dev

Head to vite-remote and open vite.config.js:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import federation from '@originjs/vite-plugin-federation'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue(), federation({
    name: 'vite-remote',
    filename: 'remoteEntry.js',
    exposes: {
      './Hello': './src/components/HelloWorld.vue'
    }
  })],
})

It is important to build the project first, in order to generate dist folder, before starting the server.

Build the project with:

npx vite build

Start the server for vite-remote you should get port 5173:

npx vite dev

Next, head to vite-host and open vite.config.js:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import federation from '@originjs/vite-plugin-federation'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue(), federation({
    name: 'vite-host',
    remotes: {
      aaa: 'http://localhost:5173/dist/assets/remoteEntry.js'
    }
  })],
})

Remove vite-host src/components/HelloWorld.vue:

rm src/components/HelloWorld.vue

Open vite-host src/App.vue:

<script setup>
// import HelloWorld from './components/HelloWorld.vue'
import HelloWorld from 'aaa/Hello'
</script>

Start the dev. server:

npx vite dev

You should get a working application in vite-host although we removed src/components/HelloWorld.vue.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *