In my current Angular 18 project, I am utilizing JSZip to compress multiple .txt files into an archive. Initially, I used the conventional JSZip syntax as shown below:
import JSZip from "jszip";
export class ScriptDatabase {
// My class code...
exportDatabase(): Promise<Blob> {
const zip = new JSZip();
for (const [id, archive] of this.archives) {
zip.file(`${id}.txt`, archive.exportArchive());
}
return zip.generateAsync({type: "blob"});
}
}
To optimize my application's final bundle size and enhance its performance, I attempted to switch to dynamic async imports. My initial approach was:
async exportDatabase(): Promise<Blob> {
const JSZip = await import('jszip');
const zip = new JSZip();
for (const [id, archive] of this.archives) {
zip.file(`${id}.txt`, archive.exportArchive());
}
return await zip.generateAsync({ type: "blob" });
}
However, I encountered a roadblock when I realized that the JSZip
constant was not a constructor, preventing me from calling new
. This led me to manipulate JSZip
differently as an instance:
async exportDatabase(): Promise<Blob> {
const JSZip = await import('jszip');
for (const [id, archive] of this.archives) {
JSZip.file(`${id}.txt`, archive.exportArchive());
}
return await JSZip.generateAsync({ type: "blob" });
}
Despite my IDE no longer showing errors and the app successfully building, executing the method resulted in an error:
ERROR TypeError: JSZip.file is not a function
.
Upon logging the object, it became evident that I had obtained an incomplete version of the JSZip object, only allowing the use of loadAsync. It's clear that my implementation was incorrect.
At this point, I am puzzled. What would be the proper syntax for incorporating JSZip with dynamic imports?