angular19angular-builder

import().then not working after upgrade to Angular 19


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:

  1. Utilizing relative path: import('../../../../node_modules/xlsx').then(xlsx => {

  2. Changing configurations from the builder

  3. Creating a new project with standard configurations then importing xlsx in the same way

Nothing worked.


Solution

  • 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.