Quando scegliere i micro frontend?
Approfondimenti (in inglese): DDD in frontend, Monorepo vs Multirepo.
I confini seguono le capacità di business, non i tipi di componenti. Catalogo e ordini possono avere team responsabili, test unitari e di integrazione e pipeline di deployment propri. Pulsanti e campi appartengono di norma al design system condiviso. Un monorepo può supportare rilasci indipendenti; più repository non garantiscono autonomia. [1][2]
Se un team modifica spesso tutte le funzioni insieme, un monolite modulare è più semplice. Misura attesa dei rilasci, modifiche coordinate e costi operativi. La divisione deve risolvere un problema organizzativo concreto.
Micro frontend e monolite modulare a confronto
| Criterio | Monolite modulare | Micro frontend |
|---|---|---|
| Deployment | Una unità di deployment | Rilasci separati con contratti compatibili |
| Autonomia dei team | Rilascio comune, moduli di dominio distinti | Cicli di rilascio indipendenti e responsabilità di dominio |
| Prestazioni | Ottimizzazione globale più semplice | Rischio di dipendenze duplicate e richieste a cascata |
| Test | Integrazione di una versione | Matrice di compatibilità e test di contratto aggiuntivi |
| UI e accessibilità | Shell e componenti comuni | Coordinamento di navigazione, focus e design system |
| Resilienza | Unità di deployment comune; isolamento degli errori possibile | Contenimento dei guasti secondo i confini di esecuzione |
| Manutenzione | Minore costo operativo iniziale | Più artefatti, pipeline e monitoraggio |
| Sicurezza | Confine di fiducia comune | Il codice nello stesso documento condivide ancora i privilegi |
| Beneficio potenziale | Cosa i micro frontend non garantiscono |
|---|---|
| Rilasci indipendenti | Compatibilità di tutte le combinazioni di versioni |
| Autonomia dei team | Assenza di dipendenze tra domini |
| Modernizzazione graduale | Migrazione senza costi di integrazione |
| Scelta tecnologica | Prestazioni migliori o minore trasferimento |
| Responsabilità di dominio | Confini corretti senza modellazione |
| Contenimento dei guasti | Isolamento di sicurezza o resilienza dell’intero prodotto |
| Sviluppo parallelo | Minore costo totale di manutenzione |
Il confronto riguarda il frontend, non la topologia backend o il numero di repository. Un monolite modulare può utilizzare microservizi e avere moduli di dominio distinti. La tabella mostra compromessi tipici, non risultati misurati garantiti. [22][23]
Modelli di integrazione
L’integrazione per route indirizza percorsi diversi ad applicazioni separate. La navigazione può ricaricare il documento, ma stato e dipendenze condivisi sono più facili da limitare. La composizione server assembla HTML prima della consegna e richiede una strategia coerente per CSS, dati, cache ed eventuale idratazione. I pacchetti npm integrati in build richiedono di ricompilare il consumatore. [1][2]
ESM, Module Federation o un orchestratore permettono di cambiare regioni nel browser senza ricostruire l’host se contratti e versioni restano compatibili. Un iframe offre un documento separato o differenti confini di fiducia, ma complica routing, accessibilità e comunicazione. [3][4][5]
Contratto tra host e remote
contract.ts
export const CONTRACT_VERSION = 1;
export type Dispose = () => void;
export interface RemoteModule {
readonly contractVersion: typeof CONTRACT_VERSION;
mount(outlet: HTMLElement): Dispose;
}
catalog/v1/entry.ts
import type { RemoteModule } from "../../contract.js";
const remote: RemoteModule = {
contractVersion: 1,
mount(outlet) {
const heading = document.createElement("h2");
heading.textContent = "Catalog";
const button = document.createElement("button");
button.type = "button";
button.textContent = "Show availability";
const message = document.createElement("p");
message.setAttribute("role", "status");
const listeners = new AbortController();
button.addEventListener(
"click",
() => {
message.textContent = "Demo item available";
},
{ signal: listeners.signal },
);
outlet.append(heading, button, message);
return () => {
listeners.abort();
outlet.replaceChildren();
};
},
};
export const { contractVersion, mount } = remote;
orders/v1/entry.ts
import type { RemoteModule } from "../../contract.js";
const remote: RemoteModule = {
contractVersion: 1,
mount(outlet) {
const heading = document.createElement("h2");
heading.textContent = "Orders";
const message = document.createElement("p");
message.textContent = "No demo orders.";
outlet.append(heading, message);
return () => {
outlet.replaceChildren();
};
},
};
export const { contractVersion, mount } = remote;
L’host gestisce navigazione e contenitore; il remote gestisce la propria funzione. Il contratto v1 richiede versione esportata e mount sincrono che restituisca una funzione di pulizia. I tipi TypeScript spariscono a runtime: l’host verifica quindi la forma del namespace. La presenza della funzione non dimostra comportamento o sicurezza. [6]
Il modulo si monta in un elemento non ancora collegato e non deve presumere misure di layout disponibili. Non modifica il DOM globale né registra effetti irreversibili a livello di modulo. Se mount fallisce deve liberare le risorse parzialmente acquisite. La navigazione sincrona rientrante è esclusa. Un prodotto può aggiungere un’attivazione dopo l’inserimento.
Import dinamico e gestione dei guasti
shell/remote-loader.ts
import { CONTRACT_VERSION } from "../contract.js";
import type { RemoteModule } from "../contract.js";
export type RemoteName = "catalog" | "orders";
export type RemoteLoader = (name: RemoteName) => Promise<unknown>;
function isObject(value: unknown): value is object {
if (value === null) {
return false;
}
return typeof value === "object";
}
export function isRemoteModule(value: unknown): value is RemoteModule {
if (!isObject(value)) {
return false;
}
if (!("contractVersion" in value)) {
return false;
}
if (value.contractVersion !== CONTRACT_VERSION) {
return false;
}
if (!("mount" in value)) {
return false;
}
return typeof value.mount === "function";
}
export async function withTimeout<T>(
work: Promise<T>,
timeoutMs: number,
): Promise<T> {
let timer: ReturnType<typeof setTimeout> | undefined;
const deadline = new Promise<never>((_, reject) => {
timer = setTimeout(() => {
reject(new Error("Module loading timed out."));
}, timeoutMs);
});
try {
return await Promise.race([work, deadline]);
} finally {
clearTimeout(timer);
}
}
shell/native-loader.ts
import type { RemoteName } from "./remote-loader.js";
const entries: Record<RemoteName, URL> = {
catalog: new URL("../catalog/v1/entry.js", import.meta.url),
orders: new URL("../orders/v1/entry.js", import.meta.url),
};
export function loadRemote(name: RemoteName): Promise<unknown> {
return import(entries[name].href);
}
shell/host.ts
import type { Dispose } from "../contract.js";
import { isRemoteModule, withTimeout } from "./remote-loader.js";
import type { RemoteLoader, RemoteName } from "./remote-loader.js";
export interface Surface {
createOutlet(): HTMLElement;
show(outlet: HTMLElement): void;
status(message: string): void;
}
const DEFAULT_TIMEOUT_MS = 10_000;
export class MicroFrontendHost {
private revision = 0;
private cleanup: Dispose | undefined;
constructor(
private readonly surface: Surface,
private readonly load: RemoteLoader,
private readonly report: (error: unknown) => void,
private readonly timeoutMs = DEFAULT_TIMEOUT_MS,
) {}
private reportFailure(error: unknown): void {
try {
this.report(error);
} catch {
// A telemetry failure must not break navigation or cleanup.
}
}
private release(): void {
const cleanup = this.cleanup;
this.cleanup = undefined;
try {
cleanup?.();
} catch (error) {
this.reportFailure(error);
}
}
async navigate(name: RemoteName): Promise<void> {
const revision = ++this.revision;
this.release();
this.surface.show(this.surface.createOutlet());
this.surface.status("Loading module…");
try {
const module = await withTimeout(this.load(name), this.timeoutMs);
if (revision !== this.revision) {
return;
}
if (!isRemoteModule(module)) {
throw new TypeError("Incompatible remote module.");
}
const outlet = this.surface.createOutlet();
const cleanup = module.mount(outlet);
if (typeof cleanup !== "function") {
throw new TypeError("Remote must return a cleanup function.");
}
this.cleanup = cleanup;
this.surface.show(outlet);
this.surface.status("");
} catch (error) {
if (revision !== this.revision) {
return;
}
this.release();
this.surface.show(this.surface.createOutlet());
this.surface.status("Module unavailable. Reload section to retry.");
this.reportFailure(error);
}
}
dispose(): void {
this.revision += 1;
this.release();
this.surface.show(this.surface.createOutlet());
this.surface.status("");
}
}
shell/main.ts
import { MicroFrontendHost } from "./host.js";
import { createManifestLoader } from "./release-manifest.js";
import type { RemoteName } from "./remote-loader.js";
function requireElement(id: string): HTMLElement {
const element = document.getElementById(id);
if (!element) {
throw new Error(`Missing element: ${id}`);
}
return element;
}
const outlet = requireElement("outlet");
const status = requireElement("status");
const retry = requireElement("retry");
const heading = requireElement("page-heading");
const links = document.querySelectorAll<HTMLAnchorElement>("nav a");
const host = new MicroFrontendHost(
{
createOutlet: () => document.createElement("section"),
show: (element) => outlet.replaceChildren(element),
status: (message) => {
status.textContent = message;
},
},
createManifestLoader(),
(error) => console.error("Micro frontend failed", error),
);
function route(): RemoteName {
if (location.hash === "#orders") {
return "orders";
}
return "catalog";
}
function renderRoute(moveFocus = false): void {
const name = route();
const title = name === "catalog" ? "Catalog" : "Orders";
document.title = `${title} | Shop`;
heading.textContent = title;
for (const link of links) {
if (link.hash === `#${name}`) {
link.setAttribute("aria-current", "page");
} else {
link.removeAttribute("aria-current");
}
}
if (moveFocus) {
heading.focus();
}
void host.navigate(name);
}
window.addEventListener("hashchange", () => renderRoute(true));
retry.addEventListener("click", () => renderRoute());
renderRoute();
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Micro frontend example</title>
<link rel="stylesheet" href="/it/shell.css" />
<script type="module" src="dist/shell/main.js"></script>
</head>
<body>
<header>
<nav aria-label="Sections">
<a href="#catalog">Catalog</a>
<a href="#orders">Orders</a>
</nav>
</header>
<main>
<h1 id="page-heading" tabindex="-1">Shop</h1>
<p id="status" role="status"></p>
<button id="retry" type="button">Reload section</button>
<div id="outlet"></div>
</main>
</body>
</html>
shell.css
body {
font-family: system-ui, sans-serif;
margin: 2rem;
line-height: 1.5;
}
nav {
display: flex;
gap: 1rem;
}
:focus-visible {
outline: 2px solid currentColor;
outline-offset: 3px;
}
L’esempio usa moduli ES nativi, non Module Federation. Le URL provengono dalla configurazione fidata dell’host, non da parametri arbitrari dell’utente. Un contatore di revisione impedisce il montaggio di risultati obsoleti. Il timeout limita l’attesa dell’host, senza annullare import ed esecuzione. [6][7]
Un errore di caricamento, versione incompatibile o mount mostra un messaggio lasciando la navigazione disponibile. Un nuovo tentativo non garantisce la rivalutazione della stessa URL, soprattutto dopo errori di esecuzione. Rimuovere il DOM non libera sottoscrizioni globali: chiama la pulizia restituita. Errori in handler successivi esulano dal try/catch di mount.
Module Federation e dipendenze
federation/webpack.config.cjs
const path = require("node:path");
const { ModuleFederationPlugin } = require("webpack").container;
const root = path.resolve(__dirname, "..");
const catalog = {
name: "catalog",
mode: "production",
entry: {},
output: {
path: path.join(root, "federated-dist/catalog/v1"),
publicPath: "auto",
uniqueName: "catalog",
},
plugins: [
new ModuleFederationPlugin({
name: "catalog",
filename: "remoteEntry.js",
exposes: {
"./feature": path.join(root, "dist/catalog/v1/entry.js"),
},
}),
],
};
const host = {
name: "shop",
mode: "production",
entry: path.join(__dirname, "host.js"),
output: {
path: path.join(root, "federated-dist/shop"),
filename: "main.js",
publicPath: "auto",
uniqueName: "shop",
},
plugins: [
new ModuleFederationPlugin({
name: "shop",
remotes: {
catalog: "catalog@../catalog/v1/remoteEntry.js",
},
}),
],
};
module.exports = [catalog, host];
federation/host.js
import { MicroFrontendHost } from "../dist/shell/host.js";
const container = document.getElementById("outlet");
const status = document.getElementById("status");
if (!container) {
throw new Error("Missing outlet.");
}
if (!status) {
throw new Error("Missing status.");
}
const host = new MicroFrontendHost(
{
createOutlet: () => document.createElement("section"),
show: (element) => container.replaceChildren(element),
status: (message) => {
status.textContent = message;
},
},
() => import("catalog/feature"),
(error) => console.error("Federated module failed", error),
);
void host.navigate("catalog");
federation/index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Federated catalog example</title>
<script defer src="main.js"></script>
</head>
<body>
<main>
<h1>Federated catalog</h1>
<p id="status" role="status"></p>
<div id="outlet"></div>
</main>
</body>
</html>
Webpack Module Federation collega moduli compilati separatamente tramite container e dipendenze condivise. Il remote espone moduli e l’host indica il container. remoteEntry.js può caricare ulteriori chunk; publicPath ne definisce la URL base. [3][8]
singleton e requiredVersion controllano la condivisione ma non eliminano ogni incompatibilità. I conflitti possono produrre avvisi o errori secondo la configurazione, per esempio strictVersion. Librerie UI comuni necessitano di contratti stabili; un singleton di stato globale spesso impone rilasci coordinati. Testa combinazioni di versioni supportate.
L’esempio webpack alternativo richiede moduli TypeScript compilati, webpack 5 e webpack-cli. Compila catalogo e shop separatamente, colloca la pagina host in /shop/index.html. È separato dall’esempio ESM e non è stato eseguito qui.
Routing, dati, stili e sicurezza
Approfondimenti (in inglese): JavaScript event propagation and delegation.
L’host gestisce route principali, lingua e navigazione. I moduli scambiano dati minimi tramite proprietà esplicite, callback o eventi versionati. Il backend applica l’autorizzazione. Non diffondere token in eventi globali. CSS Modules, prefissi e Shadow DOM limitano conflitti; token comuni favoriscono coerenza. [1]
Il codice nello stesso documento accede in generale all’ambiente JavaScript e DOM. Shadow DOM e Module Federation non sono confini di sicurezza. Per codice meno fidato valuta un origin separato e un iframe sandbox ristretto. In postMessage verifica origin, source e payload; usa targetOrigin esatto quando noto. CSP e SRI riducono rischi specifici ma non isolano script eseguiti. [4][5][9][10]
Rilasci, cache e osservabilità
Articolo correlato (in inglese): Service Workers: Caching, Offline and Updates.
Pubblica asset immutabili in percorsi versionati: carica prima tutti i file, poi aggiorna atomicamente manifesto controllato o configurazione. Conserva risorse precedenti per le sessioni attive supportate e consenti rollback del puntatore. Non sovrascrivere file con cache lunga alla stessa URL. Verifica CDN e Service Worker. [1][7][8]
L’esempio seleziona i release da un manifesto validato e li fissa per la durata del documento; build separati non sostituiscono una pipeline di distribuzione. Misura latenza di importazione, errori per release, dimensione JS e INP. Framework duplicati e richieste in cascata possono peggiorare i risultati.
v1 nel percorso identifica un rilascio, contractVersion la compatibilità dell’interfaccia; cambiano indipendentemente. Gestisci titolo e focus al cambio di route. Usa freschezza breve o rivalidazione per il manifesto e cache lunga per asset immutabili. [7]
Test di contratto e migrazione
host.test.mjs
import assert from "node:assert/strict";
import { test } from "node:test";
import { MicroFrontendHost } from "./dist/shell/host.js";
import { isRemoteModule } from "./dist/shell/remote-loader.js";
function fixture(load, timeoutMs = 1000) {
const state = { outlet: {}, status: "", errors: [] };
const host = new MicroFrontendHost(
{
createOutlet: () => ({}),
show: (outlet) => {
state.outlet = outlet;
},
status: (message) => {
state.status = message;
},
},
load,
(error) => state.errors.push(error),
timeoutMs,
);
return { host, state };
}
function remote(name, cleanup = () => {}) {
return {
contractVersion: 1,
mount(outlet) {
outlet.name = name;
return cleanup;
},
};
}
function deferred() {
let resolve;
const promise = new Promise((done) => {
resolve = done;
});
return { promise, resolve };
}
test("rejects malformed and incompatible module namespaces", () => {
// Given
const invalid = [
null,
4,
{},
{ contractVersion: 2, mount() {} },
{ contractVersion: 1, mount: false },
];
// When / Then
for (const value of invalid) {
assert.equal(isRemoteModule(value), false);
}
assert.equal(isRemoteModule(remote("catalog")), true);
});
test("mounts and releases modules on navigation", async () => {
// Given
let released = 0;
const { host, state } = fixture(async (name) =>
remote(name, () => {
released += 1;
}),
);
await host.navigate("catalog");
// When
await host.navigate("orders");
// Then
assert.equal(state.outlet.name, "orders");
assert.equal(released, 1);
host.dispose();
host.dispose();
assert.equal(released, 2);
});
test("late imports do not replace a newer route", async () => {
// Given
const slow = deferred();
const { host, state } = fixture((name) => {
if (name === "catalog") {
return slow.promise;
}
return Promise.resolve(remote(name));
});
const pending = host.navigate("catalog");
// When
await host.navigate("orders");
slow.resolve(remote("catalog"));
await pending;
// Then
assert.equal(state.outlet.name, "orders");
assert.equal(state.errors.length, 0);
});
test("a failure leaves the shell usable and can be retried", async () => {
// Given
let attempts = 0;
const { host, state } = fixture(async (name) => {
attempts += 1;
if (attempts === 1) {
throw new Error("Unavailable");
}
return remote(name);
});
// When
await host.navigate("catalog");
assert.match(state.status, /unavailable/);
await host.navigate("catalog");
// Then
assert.equal(state.status, "");
assert.equal(state.outlet.name, "catalog");
assert.equal(state.errors.length, 1);
});
test("an incompatible module never mounts", async () => {
let mounted = false;
const { host, state } = fixture(async () => ({
contractVersion: 2,
mount() {
mounted = true;
},
}));
await host.navigate("catalog");
assert.equal(mounted, false);
assert.match(state.status, /unavailable/);
});
test("timeout ignores the result of a late import", async () => {
const slow = deferred();
const { host, state } = fixture(() => slow.promise, 5);
await host.navigate("catalog");
slow.resolve(remote("catalog"));
await slow.promise;
assert.match(state.status, /unavailable/);
assert.equal(state.outlet.name, undefined);
});
test("dispose invalidates an in-flight navigation", async () => {
const slow = deferred();
const { host, state } = fixture(() => slow.promise);
const pending = host.navigate("orders");
host.dispose();
slow.resolve(remote("orders"));
await pending;
assert.equal(state.status, "");
assert.equal(state.outlet.name, undefined);
});
test("failed cleanup is reported and the next module can mount", async () => {
const { host, state } = fixture(async (name) =>
remote(name, () => {
throw new Error("Cleanup failed");
}),
);
await host.navigate("catalog");
await host.navigate("orders");
assert.equal(state.outlet.name, "orders");
assert.equal(state.errors.length, 1);
});
test("a mount exception is reported and leaves an empty outlet", async () => {
const { host, state } = fixture(async () => ({
contractVersion: 1,
mount(outlet) {
outlet.name = "partial";
throw new Error("Mount failed");
},
}));
await host.navigate("catalog");
assert.match(state.status, /unavailable/);
assert.equal(state.outlet.name, undefined);
});
test("compiled catalog and orders satisfy the runtime contract", async () => {
// Given
const names = ["catalog", "orders"];
// When / Then
for (const name of names) {
const module = await import(`./dist/${name}/v1/entry.js`);
assert.equal(isRemoteModule(module), true);
}
});
test("native loader returns the expected compiled module", async () => {
const { loadRemote } = await import("./dist/shell/native-loader.js");
const module = await loadRemote("catalog");
assert.equal(isRemoteModule(module), true);
});
test("a failing telemetry sink cannot prevent recovery", async () => {
// Given
let status = "";
const host = new MicroFrontendHost(
{
createOutlet: () => ({}),
show: () => {},
status: (message) => {
status = message;
},
},
async () => {
throw new Error("Remote failed");
},
() => {
throw new Error("Telemetry failed");
},
);
// When
await host.navigate("catalog");
// Then
assert.match(status, /unavailable/);
});
I test unitari iniettano loader e superficie di rendering per verificare ordine delle risposte, incompatibilità, timeout, pulizia e guasti. Given-When-Then separa stato iniziale, azione e risultato. I test di contratto dovrebbero importare artefatti compilati. E2E verifica navigazione, focus, problemi di rete e compatibilità dopo il rilascio. [1]
Estrai una capacità, misura il risultato e mantieni una via di ritorno al monolite modulare. Estendi soltanto se il team può rilasciare e monitorare autonomamente. Definisci responsabili dei contratti, budget di prestazioni e ritiro delle vecchie versioni.
Manifesto delle versioni e compatibilità a runtime
releases.json
{
"contractVersion": 1,
"catalog": "v1",
"orders": "v1"
}
shell/release-manifest.ts
import { CONTRACT_VERSION } from "../contract.js";
import type { RemoteLoader, RemoteName } from "./remote-loader.js";
const RELEASE_PATTERN = /^v[1-9]\d{0,8}$/u;
const MANIFEST_TIMEOUT_MS = 5_000;
type Releases = Readonly<Record<RemoteName, string>>;
type ImportModule = (url: string) => Promise<unknown>;
function readRecord(value: unknown): Record<string, unknown> {
if (value === null) {
throw new TypeError("Expected a manifest object.");
}
if (typeof value !== "object") {
throw new TypeError("Expected a manifest object.");
}
if (Array.isArray(value)) {
throw new TypeError("Expected a manifest object.");
}
return value as Record<string, unknown>;
}
function readRelease(value: unknown): string {
if (typeof value !== "string") {
throw new TypeError("Expected a release identifier.");
}
const match = value.match(RELEASE_PATTERN);
if (match?.[0] !== value) {
throw new TypeError("Invalid release identifier.");
}
return value;
}
export function parseManifest(value: unknown): Releases {
const manifest = readRecord(value);
if (manifest.contractVersion !== CONTRACT_VERSION) {
throw new TypeError("Incompatible release manifest.");
}
return Object.freeze({
catalog: readRelease(manifest.catalog),
orders: readRelease(manifest.orders),
});
}
export function createManifestLoader(
fetcher: typeof fetch = fetch,
importModule: ImportModule = (url) => import(url),
): RemoteLoader {
const manifestUrl = new URL("../../releases.json", import.meta.url);
let snapshot: Promise<Releases> | undefined;
async function fetchReleases(): Promise<Releases> {
const response = await fetcher(manifestUrl, {
cache: "no-cache",
redirect: "error",
signal: AbortSignal.timeout(MANIFEST_TIMEOUT_MS),
});
if (!response.ok) {
throw new Error(`Manifest HTTP ${response.status}.`);
}
const data: unknown = await response.json();
return parseManifest(data);
}
function getSnapshot(): Promise<Releases> {
snapshot ??= fetchReleases().catch((error: unknown) => {
snapshot = undefined;
throw error;
});
return snapshot;
}
return async (name) => {
const releases = await getSnapshot();
const path = `../${name}/${releases[name]}/entry.js`;
const url = new URL(path, import.meta.url);
return importModule(url.href);
};
}
manifest.test.mjs
import assert from "node:assert/strict";
import { test } from "node:test";
import {
createManifestLoader,
parseManifest,
} from "./dist/shell/release-manifest.js";
const release = { contractVersion: 1, catalog: "v1", orders: "v2" };
function respond(data) {
return new Response(JSON.stringify(data));
}
test("accepts a compatible manifest and freezes its snapshot", () => {
// Given / When
const snapshot = parseManifest(release);
// Then
assert.deepEqual(snapshot, { catalog: "v1", orders: "v2" });
assert.equal(Object.isFrozen(snapshot), true);
});
for (const invalid of [null, [], {}, { ...release, contractVersion: 2 }]) {
test(`rejects invalid manifest ${JSON.stringify(invalid)}`, () => {
assert.throws(() => parseManifest(invalid), TypeError);
});
}
for (const value of ["../bad", "https://bad.test/a", "v1\n", "v0", 1]) {
test(`rejects unsafe release ${JSON.stringify(value)}`, () => {
assert.throws(() => parseManifest({ ...release, catalog: value }));
});
}
test("shares one snapshot across concurrent and later imports", async () => {
// Given
let calls = 0;
const loader = createManifestLoader(async () => {
calls += 1;
return respond(release);
}, async (url) => new URL(url).pathname);
// When
const paths = await Promise.all([loader("catalog"), loader("orders")]);
await loader("catalog");
// Then
assert.equal(calls, 1);
assert.match(paths[0], /catalog\/v1\/entry\.js$/);
assert.match(paths[1], /orders\/v2\/entry\.js$/);
});
test("a failed manifest can be fetched again", async () => {
// Given
let calls = 0;
const loader = createManifestLoader(async () => {
calls += 1;
if (calls === 1) {
return new Response(null, { status: 503 });
}
return respond(release);
}, async (url) => url);
// When / Then
await assert.rejects(loader("catalog"), /503/);
assert.match(await loader("catalog"), /catalog\/v1\/entry\.js$/);
assert.equal(calls, 2);
});
test("invalid manifest is rejected before importing a module", async () => {
// Given
let imports = 0;
const loader = createManifestLoader(async () => respond({}), async () => {
imports += 1;
});
// When / Then
await assert.rejects(loader("catalog"), TypeError);
assert.equal(imports, 0);
});
test("manifest loader imports the actual compiled catalog", async () => {
// Given
const loader = createManifestLoader(async () => respond(release));
// When
const module = await loader("catalog");
// Then
assert.equal(module.contractVersion, 1);
assert.equal(typeof module.mount, "function");
});
releases.json contiene la versione del contratto e gli identificatori di catalogo e ordini. L’host usa un URL fisso, richiede la rivalidazione HTTP, rifiuta i redirect e limita la durata del recupero. Il validatore accetta solo identificatori come v1 o v2, non URL o segmenti arbitrari. Gli URL dei moduli derivano da percorsi controllati. Non è una firma crittografica né una protezione contro un’origine fidata compromessa. [6][7]
Una promessa condivisa fissa lo snapshot per la durata dell’host; la navigazione non ricarica il manifesto. Un recupero fallito può essere ripetuto e il rollback del manifesto riguarda nuove istanze. Conserva gli artefatti precedenti per i documenti attivi. Testa l’host attuale con tutti i release remoti supportati; identificatore del release e versione del contratto sono indipendenti.
Scelta degli strumenti e limiti nel 2026
Le import map native risolvono gli specificatori nel documento, ma non orchestrano il ciclo di vita. ESM tra origini richiede CORS corretto. single-spa orchestra applicazioni; Enhanced Module Federation Runtime offre mf-manifest.json, loadRemote e hook come errorLoadRemote. Il nostro manifesto semplificato non è il formato di Module Federation. Nx organizza il grafo dei progetti; Webpack, Rspack e Vite richiedono integrazioni appropriate e verifica delle versioni. [11][12][13][14][15][19][20]
Condividi solo dipendenze che richiedono un’istanza comune o danno un vantaggio misurato. I singleton non sostituiscono i test. Per SSR fissa release e dati iniziali identici su server e client, evita doppia idratazione e non eseguire codice remoto non fidato sul server. nextjs-mf documenta che App Router non è supportato e il supporto Next.js è in fase di cessazione. Non trasferire la configurazione webpack senza verificarla. [3][16][21]
Scegliere architettura e strumenti nel 2026
| Scenario | Approccio preferibile | Condizione o compromesso |
|---|---|---|
| Un team, rilasci comuni | Monolite modulare | Applicare confini di dominio e direzione delle dipendenze |
| Più team, aree di prodotto distinte | Integrazione per route | Confini di navigazione adeguati e shell coerente |
| Frammenti indipendenti nella stessa vista | ESM nativi o Module Federation | Contratti versionati, controllo dipendenze e fallback |
| Più SPA indipendenti | single-spa con ESM e import map | Ciclo di mount e unmount definito |
| Sito pubblico con esigenze SSR | Composizione server o separazione per route | Versioni compatibili, cache e idratazione |
| Codice con livello di fiducia diverso | Iframe sandbox su origine separata | Privilegi minimi e validazione dei messaggi |
Non esiste uno standard di implementazione obbligatorio. Nel 2026 il monolite modulare resta un punto di partenza sensato senza necessità di deployment indipendenti. Altrimenti valutare prima l’integrazione per route e comporre all’interno della vista quando serve un’integrazione fluida. Scegliere gli strumenti in base alla composizione, non alla popolarità del framework. [15][23][24]
Prima della migrazione definire problemi misurabili: attesa dei rilasci comuni, quota di modifiche coordinate, tempo di ripristino e budget prestazionali. Confrontare il progetto pilota con la situazione iniziale. Servono standard comuni di CI/CD, contratti, accessibilità, sicurezza e telemetria. Non esiste una soglia universale per numero di team o dimensioni. [23][25]
Operatività e criteri di accettazione
Assegna responsabili a domini, contratti e manifesto. In CI testa l’host con i release supportati, asset mancanti, incompatibilità, latenza e pulizia. Distribuisci gradualmente, monitora per release e interrompi al superamento delle soglie concordate di errori o latenza. Il rollback del puntatore non annulla codice già eseguito o migrazioni backend incompatibili.
Definisci budget di trasferimento e disponibilità del modulo, monitora INP della pagina. Alcune misure Resource Timing tra origini richiedono Timing-Allow-Origin indipendentemente da CORS. OpenTelemetry può aiutare la correlazione, ma la strumentazione browser è ancora sperimentale. Non inviare token o dati personali. L’host aggiorna titolo e aria-current, sposta il focus sul titolo al cambio di percorso e recupera anche se la segnalazione degli errori fallisce. [17][18]
