Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(module-federation): use module-federation runtime for dynamic federation #28704

Merged
merged 6 commits into from
Nov 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions e2e/react/src/react-module-federation.rspack.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1189,7 +1189,7 @@ describe('React Rspack Module Federation', () => {
`${shell}/src/assets/module-federation.manifest.json`,
(json) => {
return {
[remote]: `http://localhost:${remotePort}`,
[remote]: `http://localhost:${remotePort}/mf-manifest.json`,
};
}
);
Expand All @@ -1198,7 +1198,9 @@ describe('React Rspack Module Federation', () => {
`${shell}/src/assets/module-federation.manifest.json`
);
expect(manifest[remote]).toBeDefined();
expect(manifest[remote]).toEqual('http://localhost:4205');
expect(manifest[remote]).toEqual(
'http://localhost:4205/mf-manifest.json'
);

// update e2e
updateFile(
Expand Down
6 changes: 4 additions & 2 deletions e2e/react/src/react-module-federation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1015,7 +1015,7 @@ describe('React Module Federation', () => {
`${shell}/src/assets/module-federation.manifest.json`,
(json) => {
return {
[remote]: `http://localhost:${remotePort}`,
[remote]: `http://localhost:${remotePort}/mf-manifest.json`,
};
}
);
Expand All @@ -1024,7 +1024,9 @@ describe('React Module Federation', () => {
`${shell}/src/assets/module-federation.manifest.json`
);
expect(manifest[remote]).toBeDefined();
expect(manifest[remote]).toEqual('http://localhost:4205');
expect(manifest[remote]).toEqual(
'http://localhost:4205/mf-manifest.json'
);

// update e2e
updateFile(
Expand Down
64 changes: 64 additions & 0 deletions packages/angular/mf/mf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ declare const __webpack_share_scopes__: { default: unknown };

let resolveRemoteUrl: ResolveRemoteUrlFunction;

/**
* @deprecated Use Runtime Helpers from '@module-federation/enhanced/runtime' instead. This will be removed in Nx 22.
*/
export function setRemoteUrlResolver(
_resolveRemoteUrl: ResolveRemoteUrlFunction
) {
Expand All @@ -15,10 +18,56 @@ export function setRemoteUrlResolver(

let remoteUrlDefinitions: Record<string, string>;

/**
* @deprecated Use init() from '@module-federation/enhanced/runtime' instead. This will be removed in Nx 22.
* If you have a remote app called `my-remote-app` and you want to use the `http://localhost:4201/mf-manifest.json` as the remote url, you should change it from:
* ```ts
* import { setRemoteDefinitions } from '@nx/angular/mf';
*
* setRemoteDefinitions({
* 'my-remote-app': 'http://localhost:4201/mf-manifest.json'
* });
* ```
* to use init():
* ```ts
* import { init } from '@module-federation/enhanced/runtime';
*
* init({
* name: 'host',
* remotes: [{
* name: 'my-remote-app',
* entry: 'http://localhost:4201/mf-manifest.json'
* }]
* });
* ```
*/
export function setRemoteDefinitions(definitions: Record<string, string>) {
remoteUrlDefinitions = definitions;
}

/**
* @deprecated Use registerRemotes() from '@module-federation/enhanced/runtime' instead. This will be removed in Nx 22.
* If you set a remote app with `setRemoteDefinition` such as:
* ```ts
* import { setRemoteDefinition } from '@nx/angular/mf';
*
* setRemoteDefinition(
* 'my-remote-app',
* 'http://localhost:4201/mf-manifest.json'
* );
* ```
* change it to use registerRemotes():
* ```ts
* import { registerRemotes } from '@module-federation/enhanced/runtime';
*
* registerRemotes([
* {
* name: 'my-remote-app',
* entry: 'http://localhost:4201/mf-manifest.json'
* }
* ]);
* ```
*/
export function setRemoteDefinition(remoteName: string, remoteUrl: string) {
remoteUrlDefinitions ??= {};
remoteUrlDefinitions[remoteName] = remoteUrl;
Expand All @@ -27,6 +76,21 @@ export function setRemoteDefinition(remoteName: string, remoteUrl: string) {
let remoteModuleMap = new Map<string, unknown>();
let remoteContainerMap = new Map<string, unknown>();

/**
* @deprecated Use loadRemote() from '@module-federation/enhanced/runtime' instead. This will be removed in Nx 22.
* If you set a load a remote with `loadRemoteModule` such as:
* ```ts
* import { loadRemoteModule } from '@nx/angular/mf';
*
* loadRemoteModule('my-remote-app', './Module').then(m => m.RemoteEntryModule);
* ```
* change it to use loadRemote():
* ```ts
* import { loadRemote } from '@module-federation/enhanced/runtime';
*
* loadRemote<typeof import('my-remote-app/Module')>('my-remote-app/Module').then(m => m.RemoteEntryModule);
* ```
*/
export async function loadRemoteModule(remoteName: string, moduleName: string) {
const remoteModuleKey = `${remoteName}:${moduleName}`;
if (remoteModuleMap.has(remoteModuleKey)) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,32 +1,34 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`Init MF --federationType=dynamic should create a host with the correct configurations 1`] = `
"import { setRemoteDefinitions } from '@nx/angular/mf';
"import { init } from '@module-federation/enhanced/runtime';

fetch('/module-federation.manifest.json')
.then((res) => res.json())
.then(definitions => setRemoteDefinitions(definitions))
.then((remotes: Record<string, string>) => Object.entries(remotes).map(([name, entry]) => ({ name,entry})))
.then(remotes => init({name: 'app1', remotes}))
.then(() => import('./bootstrap').catch(err => console.error(err)));"
`;

exports[`Init MF --federationType=dynamic should create a host with the correct configurations when --typescriptConfiguration=true 1`] = `
"import { setRemoteDefinitions } from '@nx/angular/mf';
"import { init } from '@module-federation/enhanced/runtime';

fetch('/module-federation.manifest.json')
.then((res) => res.json())
.then(definitions => setRemoteDefinitions(definitions))
.then((remotes: Record<string, string>) => Object.entries(remotes).map(([name, entry]) => ({ name,entry})))
.then(remotes => init({name: 'app1', remotes}))
.then(() => import('./bootstrap').catch(err => console.error(err)));"
`;

exports[`Init MF --federationType=dynamic should wire up existing remote to dynamic host correctly 1`] = `
"import { NxWelcomeComponent } from './nx-welcome.component';
import { Route } from '@angular/router';
import { loadRemoteModule } from '@nx/angular/mf';
import { loadRemote } from '@module-federation/enhanced/runtime';

export const appRoutes: Route[] = [
{
path: 'remote1',
loadChildren: () => loadRemoteModule('remote1', './Module').then(m => m.RemoteEntryModule)
loadChildren: () => loadRemote<typeof import('remote1/Module')>('remote1/Module').then(m => m!.RemoteEntryModule)
},
{
path: '',
Expand All @@ -38,12 +40,12 @@ export const appRoutes: Route[] = [
exports[`Init MF --federationType=dynamic should wire up existing remote to dynamic host correctly when --typescriptConfiguration=true 1`] = `
"import { NxWelcomeComponent } from './nx-welcome.component';
import { Route } from '@angular/router';
import { loadRemoteModule } from '@nx/angular/mf';
import { loadRemote } from '@module-federation/enhanced/runtime';

export const appRoutes: Route[] = [
{
path: 'remote1',
loadChildren: () => loadRemoteModule('remote1', './Module').then(m => m.RemoteEntryModule)
loadChildren: () => loadRemote<typeof import('remote1/Module')>('remote1/Module').then(m => m!.RemoteEntryModule)
},
{
path: '',
Expand All @@ -59,11 +61,11 @@ import { Route } from '@angular/router';
export const appRoutes: Route[] = [
{
path: 'remote2',
loadChildren: () => import('remote2/Module').then(m => m.RemoteEntryModule)
loadChildren: () => import('remote2/Module').then(m => m!.RemoteEntryModule)
},
{
path: 'remote1',
loadChildren: () => import('remote1/Module').then(m => m.RemoteEntryModule)
loadChildren: () => import('remote1/Module').then(m => m!.RemoteEntryModule)
},
{
path: '',
Expand Down Expand Up @@ -175,12 +177,12 @@ export default config;
exports[`Init MF should add a remote to dynamic host correctly 1`] = `
"import { NxWelcomeComponent } from './nx-welcome.component';
import { Route } from '@angular/router';
import { loadRemoteModule } from '@nx/angular/mf';
import { loadRemote } from '@module-federation/enhanced/runtime';

export const appRoutes: Route[] = [
{
path: 'remote1',
loadChildren: () => loadRemoteModule('remote1', './Module').then(m => m.RemoteEntryModule)
loadChildren: () => loadRemote<typeof import('remote1/Module')>('remote1/Module').then(m => m!.RemoteEntryModule)
},
{
path: '',
Expand All @@ -192,12 +194,12 @@ export const appRoutes: Route[] = [
exports[`Init MF should add a remote to dynamic host correctly when --typescriptConfiguration=true 1`] = `
"import { NxWelcomeComponent } from './nx-welcome.component';
import { Route } from '@angular/router';
import { loadRemoteModule } from '@nx/angular/mf';
import { loadRemote } from '@module-federation/enhanced/runtime';

export const appRoutes: Route[] = [
{
path: 'remote1',
loadChildren: () => loadRemoteModule('remote1', './Module').then(m => m.RemoteEntryModule)
loadChildren: () => loadRemote<typeof import('remote1/Module')>('remote1/Module').then(m => m!.RemoteEntryModule)
},
{
path: '',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,12 @@ export function addRemoteToHost(tree: Tree, options: AddRemoteOptions) {
isHostUsingTypescriptConfig
);
} else if (hostFederationType === 'dynamic') {
addRemoteToDynamicHost(tree, options, pathToMFManifest);
addRemoteToDynamicHost(
tree,
options,
pathToMFManifest,
hostProject.sourceRoot
);
}

addLazyLoadedRouteToHostAppModule(tree, options, hostFederationType);
Expand Down Expand Up @@ -114,17 +119,23 @@ function addRemoteToStaticHost(
function addRemoteToDynamicHost(
tree: Tree,
options: AddRemoteOptions,
pathToMfManifest: string
pathToMfManifest: string,
hostSourceRoot: string
) {
// TODO(Colum): Remove for Nx 22
const usingLegacyDynamicFederation = tree
.read(`${hostSourceRoot}/main.ts`, 'utf-8')
.includes('setRemoteDefinitions(');
updateJson(tree, pathToMfManifest, (manifest) => {
return {
...manifest,
[options.appName]: `http://localhost:${options.port}`,
[options.appName]: `http://localhost:${options.port}${
usingLegacyDynamicFederation ? '' : '/mf-manifest.json'
}`,
};
});
}

// TODO(colum): future work: allow dev to pass to path to routing module
function addLazyLoadedRouteToHostAppModule(
tree: Tree,
options: AddRemoteOptions,
Expand All @@ -150,34 +161,49 @@ function addLazyLoadedRouteToHostAppModule(
true
);

// TODO(Colum): Remove for Nx 22
const usingLegacyDynamicFederation =
hostFederationType === 'dynamic' &&
tree
.read(`${hostAppConfig.sourceRoot}/main.ts`, 'utf-8')
.includes('setRemoteDefinitions(');

if (hostFederationType === 'dynamic') {
sourceFile = insertImport(
tree,
sourceFile,
pathToHostRootRouting,
'loadRemoteModule',
'@nx/angular/mf'
usingLegacyDynamicFederation ? 'loadRemoteModule' : 'loadRemote',
usingLegacyDynamicFederation
? '@nx/angular/mf'
: '@module-federation/enhanced/runtime'
);
}

const routePathName = options.standalone ? 'Routes' : 'Module';
const exportedRemote = options.standalone
? 'remoteRoutes'
: 'RemoteEntryModule';
const remoteModulePath = `${options.appName.replace(
/-/g,
'_'
)}/${routePathName}`;
const routeToAdd =
hostFederationType === 'dynamic'
? `loadRemoteModule('${options.appName.replace(
/-/g,
'_'
)}', './${routePathName}')`
: `import('${options.appName.replace(/-/g, '_')}/${routePathName}')`;
? usingLegacyDynamicFederation
? `loadRemoteModule('${options.appName.replace(
/-/g,
'_'
)}', './${routePathName}')`
: `loadRemote<typeof import('${remoteModulePath}')>('${remoteModulePath}')`
: `import('${remoteModulePath}')`;

addRoute(
tree,
pathToHostRootRouting,
`{
path: '${options.appName}',
loadChildren: () => ${routeToAdd}.then(m => m.${exportedRemote})
loadChildren: () => ${routeToAdd}.then(m => m!.${exportedRemote})
}`
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,12 @@ export function fixBootstrap(tree: Tree, appRoot: string, options: Schema) {
manifestPath = '/module-federation.manifest.json';
}

const fetchMFManifestCode = `import { setRemoteDefinitions } from '@nx/angular/mf';
const fetchMFManifestCode = `import { init } from '@module-federation/enhanced/runtime';

fetch('${manifestPath}')
.then((res) => res.json())
.then(definitions => setRemoteDefinitions(definitions))
.then((remotes: Record<string, string>) => Object.entries(remotes).map(([name, entry]) => ({ name,entry})))
.then(remotes => init({name: '${options.appName}', remotes}))
.then(() => ${bootstrapImportCode});`;

tree.write(mainFilePath, fetchMFManifestCode);
Expand Down
8 changes: 4 additions & 4 deletions packages/angular/src/generators/setup-mf/setup-mf.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -574,7 +574,7 @@ describe('Init MF', () => {
expect(
readJson(tree, 'app1/public/module-federation.manifest.json')
).toEqual({
remote1: 'http://localhost:4201',
remote1: 'http://localhost:4201/mf-manifest.json',
});
expect(
tree.read('app1/src/app/app.routes.ts', 'utf-8')
Expand Down Expand Up @@ -609,7 +609,7 @@ describe('Init MF', () => {
expect(
readJson(tree, 'app1/public/module-federation.manifest.json')
).toEqual({
remote1: 'http://localhost:4201',
remote1: 'http://localhost:4201/mf-manifest.json',
});
expect(
tree.read('app1/src/app/app.routes.ts', 'utf-8')
Expand Down Expand Up @@ -648,7 +648,7 @@ describe('Init MF', () => {
expect(
readJson(tree, 'app1/public/module-federation.manifest.json')
).toEqual({
remote1: 'http://localhost:4201',
remote1: 'http://localhost:4201/mf-manifest.json',
});
expect(tree.read('app1/src/app/app.routes.ts', 'utf-8')).toMatchSnapshot();
});
Expand Down Expand Up @@ -684,7 +684,7 @@ describe('Init MF', () => {
expect(
readJson(tree, 'app1/public/module-federation.manifest.json')
).toEqual({
remote1: 'http://localhost:4201',
remote1: 'http://localhost:4201/mf-manifest.json',
});
expect(tree.read('app1/src/app/app.routes.ts', 'utf-8')).toMatchSnapshot();
});
Expand Down
5 changes: 3 additions & 2 deletions packages/angular/src/generators/setup-mf/setup-mf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,12 @@ export async function setupMf(tree: Tree, rawOptions: Schema) {
if (!options.skipPackageJson) {
installTask = addDependenciesToPackageJson(
tree,
{},
{
'@module-federation/enhanced': moduleFederationEnhancedVersion,
},
{
'@nx/web': nxVersion,
'@nx/webpack': nxVersion,
'@module-federation/enhanced': moduleFederationEnhancedVersion,
}
);
}
Expand Down
Loading