At work our design system isn't published to npm but deployed as a webpack Module Federation remote called shared_components, which the apps load at runtime, and the one thing that setup doesn't come with is types, since import Table from 'shared_components/Table' has none out of the box. TypeScript has no idea that shared_components is a script loaded at runtime from another server, so the import either fails with "Cannot find module" or, if someone has added a declare module 'shared_components/*', everything coming from it is any, which is worse since it compiles. This is how the remote ships its real declarations to the apps, and the couple of odd files that make it work.
Generating the declarations
The remote runs dts-loader on its TypeScript files, next to babel-loader, with the same name and exposes that go to ModuleFederationPlugin:
{
test: /\.tsx?$/,
use: [
{ loader: 'babel-loader', options: { /* … */ } },
{
loader: 'dts-loader',
options: {
name: federationConfig.name, // 'shared_components'
exposes: federationConfig.exposes,
},
},
],
}
For every TypeScript file webpack loads, the loader asks the TypeScript language service for its declaration and writes it under .wp_federation/shared_components/dts/, and when the file is also an entry in exposes it writes a small entry file named after the key:
// .wp_federation/shared_components/Table.d.ts
export * from './dts/src/components/Table/index';
export { default } from './dts/src/components/Table/index';
So the import shared_components/Table lines up with the file shared_components/Table.d.ts, which is exactly what we need on the other end.
The loader writes
export { default }for every exposed module, including ones like./hooksthat have no default export, which is an error in the generated file that nobody ever sees because the apps build withskipLibCheck.
After the build, a small script packs the folder into a .tgz that is deployed next to remoteEntry.js, so the types of a deployment are served from the same place as its code:
// scripts/compressTypes.js (simplified)
fs.copyFileSync('./scripts/index.d.ts.template', './.wp_federation/shared_components/index.d.ts');
execSync('node scripts/copyTypeDefs.js');
execSync('tar czf dist/assets/shared_components-dts.tgz -C ./.wp_federation shared_components');
Where the apps put them
Every app downloads that archive before each build and unpacks it into node_modules/@types:
// scripts/getRemoteTypes.js (simplified)
const fs = require('fs');
const { execSync } = require('child_process');
const archive = './shared_components-dts.tgz';
const url = 'https://design-system.stage.example.com/assets/shared_components-dts.tgz';
async function main() {
if (!fs.existsSync(archive) || process.argv.includes('-f')) {
const response = await fetch(url);
if (!response.ok) throw new Error(`Could not download types: ${response.status}`);
fs.writeFileSync(archive, Buffer.from(await response.arrayBuffer()));
}
fs.mkdirSync('./node_modules/@types', { recursive: true });
execSync(`tar xzf ${archive} -C ./node_modules/@types`);
}
main();
// webpack.config.js
new WebpackShellPluginNext({
onBuildStart: {
scripts: ['node scripts/getRemoteTypes.js'],
blocking: true,
},
}),
The archive is gitignored and reused when it's already there, so builds don't hit the network every time, but that also means after a design system deploy someone has to run the script with -f to download the new one. Nobody remembers to, so our newer apps also run it from an afterInstall hook (a small third-party Yarn plugin) after every yarn install.
Unpacking into node_modules/@types is the reason none of the apps have a paths entry or a hand-written declaration for the design system. With moduleResolution: "node", TypeScript resolves shared_components/Table by looking for a shared_components package in node_modules, and when it doesn't find one it tries node_modules/@types/shared_components/Table.d.ts (the same lookup that finds @types/react), which is where the archive put the file.
The catch is that, unless the tsconfig sets types, TypeScript also loads every folder in node_modules/@types as a type package on its own, and a folder without an index.d.ts fails the whole compile:
error TS2688: Cannot find type definition file for 'shared_components'.
So the remote ships an empty one:
// scripts/index.d.ts.template
// dummy index.d.ts file to make the TS compiler happy
// @see https://github.com/Microsoft/TypeScript/issues/27956
export {};
The other script, copyTypeDefs.js, is there because the theme's declarations import our MUI theme augmentation (the extra palette colors) from a file outside the archive, so it copies that augmentation into the theme's generated declaration, and the apps get it with the rest of the types.
Webpack's filesystem cache and the loader
dts-loader writes the declarations as a side effect of loading a module, and with webpack's filesystem cache a module that hasn't changed is restored from the cache and not built again, so its loaders don't run. If someone deletes .wp_federation (which happens when you clean things up), the next build is fast and writes no types at all. Webpack doesn't know that folder exists, so we made the cache depend on it by putting its existence into the cache version:
// webpack.config.js
const federatedTypesPath = path.resolve(__dirname, '.wp_federation');
module.exports = {
// …
cache: {
type: 'filesystem',
version: `federatedTypesPath_${fs.existsSync(federatedTypesPath)}`,
},
};
When webpack starts and the folder is missing, the version changes, so the old cache isn't reused and the loader runs for every file again (the build after that is cold too, since by then the folder exists and the version flips back).
The easiest place we found for a remote's declarations is node_modules/@types/<remote name>, because then TypeScript resolves the remote's imports with its normal lookup and the apps need no TypeScript config for it, as long as the folder has an index.d.ts and carries everything its declarations import, like the theme augmentation in our case. And when a loader writes files as a side effect, the filesystem cache has to know about those files, otherwise a cached build skips them without any error.
Top comments (0)