Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Minified version of XLSX on Angular 5?

Is there a correct way to use minified XLSX on an Angular 5 project?

Currently I'm using it as:

import * as XLSX from 'xlsx';

Using this import like:

const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json);

And

const workbook: XLSX.WorkBook = XLSX.utils.book_new();

It works just fine, but produces a very large bundle object inside my build: enter image description here

I want to know if it's possible to use the .min files, to help reduce the bundle size. And if so, how to import and use it properly?

like image 493
rscherer Avatar asked May 09 '18 17:05

rscherer


1 Answers

This is how I did it in Angular:

    import('xlsx').then(xlsx => {});

It is triggered only when a user clicks on my excel service button :) It seems like 'bad practice' but the xlsx can't really be minified properly.. anyway, it saved me 1.2MB on my bundle!

Discussion on GitHub: https://github.com/SheetJS/sheetjs/issues/694#issuecomment-688310069

Getting the types requires extra (but yet easy) work - read this: How to use types with dynamic imports?

I was inspired by this developer, who encountered the same problem: https://netbasal.com/using-typescript-dynamic-imports-in-angular-d210547484dd

    import { Injectable } from '@angular/core';
    import * as FileSaver from 'file-saver';

    // import * as XLSX from 'xlsx';
    // import { utils, write } from 'xlsx';
    // import { WorkSheet, WorkBook } from 'xlsx';

    const EXCEL_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
    const EXCEL_EXTENSION = '.xlsx';
    
    @Injectable()
    export class ExcelService {
    
      constructor() { }
    
      public exportAsExcelFile(arrOfObjs: {}[], excelFileName: string): void {
        import('xlsx').then(xlsx => {
          // console.log(xlsx);
          const worksheet: import('xlsx').WorkSheet = xlsx.utils.json_to_sheet(arrOfObjs);
          console.log('worksheet', worksheet);
          const wb: import('xlsx').WorkBook = { Sheets: { data: worksheet }, SheetNames: ['data'] };
          if (!wb.Workbook) { wb.Workbook = {}; }
          if (!wb.Workbook.Views) { wb.Workbook.Views = []; }
          if (!wb.Workbook.Views[0]) { wb.Workbook.Views[0] = {}; }
          wb.Workbook.Views[0].RTL = true;
          const excelBuffer: BlobPart = xlsx.write(wb, { bookType: 'xlsx', type: 'array' });
          this.saveAsExcelFile(excelBuffer, excelFileName);
        });
      }
    
      private saveAsExcelFile(buffer: BlobPart, fileName: string): void {
        const data: Blob = new Blob([buffer], {
          type: EXCEL_TYPE
        });
        FileSaver.saveAs(data, fileName + '_export_' + new Date().getTime() + EXCEL_EXTENSION);
      }
    }

like image 163
Itay Avatar answered Oct 20 '22 17:10

Itay