Last active
November 18, 2024 20:54
-
-
Save gilvam/8d2078e5cd7c26467dff4792ccdd4307 to your computer and use it in GitHub Desktop.
module federation test reload remoteEntry.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const routes: Routes = [ | |
{ | |
path: 'x', | |
component: XComponent, | |
}, | |
{ | |
path: 'xpto', | |
component: WebComponentWapper, | |
data: { | |
remoteEntry: 'https://www.xxx.com:4000/remoteEntry.js', | |
remoteName: 'xpto', | |
type: 'module', | |
exposedModule: './web-components', | |
elementName: 'xpto', | |
retryAttempts: 3, // Quantas tentativas antes de falhar | |
} as WebComponentWrapperOptions, | |
resolve: { | |
remote: RemoteLoaderResolver // Resolver personalizado | |
}, | |
}, | |
]; | |
import { Injectable } from '@angular/core'; | |
import { Resolve, ActivatedRouteSnapshot, Router } from '@angular/router'; | |
@Injectable({ providedIn: 'root' }) | |
export class RemoteLoaderResolver implements Resolve<Promise<void>> { | |
async resolve(route: ActivatedRouteSnapshot): Promise<void> { | |
const data = route.data as WebComponentWrapperOptions; | |
const remoteEntry = data.remoteEntry; | |
const retryAttempts = data.retryAttempts || 1; | |
for (let attempt = 0; attempt < retryAttempts; attempt++) { | |
try { | |
await loadRemoteScript(remoteEntry); | |
console.log(`Loaded remoteEntry.js on attempt ${attempt + 1}`); | |
return; | |
} catch (error) { | |
console.error(`Attempt ${attempt + 1} failed to load remoteEntry.js`); | |
if (attempt === retryAttempts - 1) { | |
throw error; // Lança erro após todas as tentativas | |
} | |
} | |
} | |
} | |
} | |
function loadRemoteScript(remoteEntry: string, timeout = 5000): Promise<void> { | |
return new Promise((resolve, reject) => { | |
const script = document.createElement('script'); | |
script.src = remoteEntry; | |
script.type = 'text/javascript'; | |
script.async = true; | |
const timer = setTimeout(() => { | |
reject(new Error(`Timeout loading remoteEntry: ${remoteEntry}`)); | |
script.remove(); | |
}, timeout); | |
script.onload = () => { | |
clearTimeout(timer); | |
resolve(); | |
}; | |
script.onerror = () => { | |
clearTimeout(timer); | |
reject(new Error(`Failed to load remoteEntry: ${remoteEntry}`)); | |
}; | |
document.body.appendChild(script); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment