javascriptangulartypescriptimportes6-modules

dynamically import es module provided as a blob with es-mdoule-shims and angulars native federation


Problem

I am developing a plugin based architecture in angularjs. To load a plugin in runtime I first send a request to the backend to download and store the plugins source code. This way I already have the source code available when loading the plugin in the future.

However when trying to import this source code in the frontend I have the following problem: Because I am using openapis typescript-angular generator I dont have an explicit url to use inside await import(<url>) but rather an autogenerated service that returns an Observable<Blob>. Of course I could use the plugins url to import the plugin directly from its remote but this way I have to fetch it every time I want to import it (eg on startups).

What I tried

  1. Creating a blob url using URL.createObjectUrl(<blob>) and import it, but I am using angulars native federation which internally uses es-module-shims and it throws the error TypeError: Failed to construct 'URL': Invalid URL
  2. Same problem with data urls:
    const reader = new FileReader();
    reader.onload = async function () {
        const blobAsDataUrl: string = reader.result as string;
        const module = await import(blobAsDataUrl);
    };

    reader.readAsDataURL(<blob>);
  1. creating a script tag with type=module-shim and using innerHTML to inject the plugins source code does work, but then I dont have access to the plugins exports and because every plugin exports a function called initialize I cannot use global scope.

Solution

  • This was an issue in the polyfill es-module-shims and is fixed in v1.10.1 (github issue)