mheonyae
mheonyae

Reputation: 643

Microfrontend Module Federation using vite/react/typescript: Cannot find module

I am trying to setup a microfrontend for my project and at base I am using vite to setup my react/typescript applications. I've installed the vite plugin for module federation.

And these are my vite.config.ts:

Host:

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



export default defineConfig({
  build: {
    target: 'esnext' 
  },
  plugins: [react(),
  federation({
    name: "app",
    remotes: {
      "remote": "http://localhost:5001/assets/remoteEntry.js",
    },
    shared: ["react", "react-dom"],
  })
  ],
})

remote:

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



export default defineConfig({
  build: {
    target: 
  },
  plugins: [react(),
  federation({
    name: "remote",
    filename: 'remoteEntry.js',
    exposes: {
      "Button": "./src/components/Button",
    },
    shared: ["react", "react-dom"],
  })

  ],
  server: {
    port: 5001,
  },
})

When i import the shared button in my host application i get this error:

src/App.tsx:3:20 - error TS2307: Cannot find module 'remote/Button' or its corresponding type declarations.

I am running the remote app on 5001 port. I am lost at what I am missing, hope anyone can help me out - if more context/info is needed I'm happy to provide more.

Upvotes: 1

Views: 10812

Answers (4)

Joshua Duxbury
Joshua Duxbury

Reputation: 5260

If using typescript you need to have a tsremote_declarations.ts file with the module in. A big mistake for me was calling the file tsremote_declarations.ts, changing this to tsremote_.d.ts worked as it looks to be name depandant

Upvotes: 0

Sidou Gmr
Sidou Gmr

Reputation: 126

create file name declaration.d.ts in src host and add this

declare module 'remote/Button'

Upvotes: 0

Ricardo Marcattini
Ricardo Marcattini

Reputation: 51

Just create a file inside src/ folder, name it something like remotes.d.ts, and add the following line

declare module 'remote/Button'

  • first (remote) is the name you use in you host vite.config.ts
  • second (Button) is the name you exposes in you remote vite.config.ts

or just add

declare module 'remote/*'

to declare all incoming modules under remote

Upvotes: 5

Dave
Dave

Reputation: 228

I came across this article while searching for micro-frontend module federation. https://software-engineering-corner.hashnode.dev/micro-frontend-module-federation-with-vite-for-react#heading-as-a-lazy-loaded-module

See the code block below NOTE: If you prefer to implement this using typescript...

Looks like you have to bring your own types.

Upvotes: 1

Related Questions