How to keep types while using module federation?

Josh Lin
2 min readJul 8, 2021

That is a good question, let’s break it down first

  • module federation
  • typescript

Module Federation

When you use module federation it gonna big big project, call it Micro Frontends or whatever

Suppose use case:

  • too big a project(monolith frontend) that webpack will eat all memories and take a really long time to build, that will hurt productivity
  • already using typescript for type checking and hinting

then we separate big project into smaller packages, and use each other through npm install this helps a lot but not the building time, to reduce the building time, it has to be something like module federation or require.js

ES module is not in the list to compare, and it’s the best choice if all your users use morden browsers. And if not, I choose module federation which is more webpack and more trending

TypeScript

We like hints and auto completion, and in big project, complecated nested types, interfaces will help a lot

Back to the problem at beginning

When we use module federation, the types got lost, but redefine types surely mean huge cost

Fixing types

Npm packages built with TypeScript can keep their types, so we build such kind of packages

1st, name exposed according to tsc output path

2nd run both tsc and webpack build to build package and install where will use it

See? types are there. And a working example here:

--

--