I need to import libraries that are not ESM compliant.
One of them is called xlsx (SheetJS).
When working with Angular 17 and earlier versions, I just did:
import('xlsx').then(xlsx => {
const ws: any = xlsx.utils.json_to_sheet(json);
const wb: any = xlsx.utils.book_new();
xlsx.utils.book_append_sheet(wb, ws, 'teste9');
xlsx.writeFile(wb, 'test.xlsx');
});
Now that I upgraded the project to version 19, the same code results in error:
ERROR TypeError: Cannot read properties of undefined (reading 'json_to_sheet')
During ng serve, the code works fine. Only after ng build this starts hapenning.
I've tried:
Utilizing relative path: import('../../../../node_modules/xlsx').then(xlsx => {
Changing configurations from the builder
Creating a new project with standard configurations then importing xlsx in the same way
Nothing worked.
While reviewing the console.log
output from the libraries, I noticed that all the functionality was still present. However, this time it was nested under module > default
, whereas previously it was directly under default
.
import('xlsx').then(xlsx => {
const ws: any = xlsx.default.utils.json_to_sheet(json);
const wb: any = xlsx.default.utils.book_new();
xlsx.default.utils.book_append_sheet(wb, ws, nomeDaPlanilha);
xlsx.default.writeFile(wb, 'test.xlsx');
});
Several Stack Overflow posts claimed that dynamic imports of dependencies were no longer possible after Angular 18. However, it's working perfectly fine now.