d-band / better-xlsx

A better xlsx library.
https://d-band.github.io/better-xlsx/
420 stars 36 forks source link

Issues with create-react-app and uglify #62

Closed klozowski closed 6 years ago

klozowski commented 6 years ago

I had a couple of issues with this library while using create-react-app, which invokes uglify for minification as a plugin for webpack (browser-only use). First, it refuses to compile with uglify's minification turned on, referring to the following URL:

https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md#npm-run-build-fails-to-minify

this can be remedied by importing the precompiled version in dist/ into my react app instead of importing the library's root dir as i do with the other npm libs i use.

However, even after resolving this minor issue, create-react-app's uglify settings break the code that generates XML nodes, causing them to generate empty node names in the rendered xml files and the excel file to register as corrupted. This happens whether I import the precompiled version or copy the library's source files into my react app and import them from there. I'm unsure what is different between the use of uglify that builds the distribution files and the use of uglify in create-react-app but it would be lovely if this lib would work out of the box with create-react-app.

helloyou2012 commented 6 years ago

@klozowski importing the compiled version is ok. you can try like this:

import React, { Component } from 'react';
import xlsx from 'better-xlsx/dist/xlsx';
import FileSaver from 'file-saver';

class App extends Component {
  save() {
    const file = new xlsx.File();
    const sheet = file.addSheet('Sheet1');
    const row = sheet.addRow();
    const cell = row.addCell();

    cell.value = 'I am a cell!';
    cell.hMerge = 2;
    cell.vMerge = 1;

    cell.style.fill.patternType = 'solid';
    cell.style.fill.fgColor = '00FF0000';
    cell.style.fill.bgColor = 'FF000000';
    cell.style.align.h = 'center';
    cell.style.align.v = 'center';

    file.saveAs('blob').then((content) => {
      FileSaver.saveAs(content, "example.xlsx");
    });
  }
  render() {
    return (
      <div className="App">
        <button onClick={() => this.save()}>Download</button>
      </div>
    );
  }
}