Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correctly importing LZString in webpack project

I'm trying import LZString 1.4.4 to my webpack project, however I'm getting this error in chrome console:

core.es5.js?de3d:1020 ERROR TypeError: Cannot read property 'compress' of undefined
at FileReader.reader.onload (file-upload.ts?e535:117)
at ZoneDelegate.invoke (zone.js?6524:392)
at Object.onInvoke (core.es5.js?de3d:3890)
at ZoneDelegate.invoke (zone.js?6524:391)
at Zone.runGuarded (zone.js?6524:155)
at FileReader.eval (zone.js?6524:133)

I'm importing LZString this way:

import { LZString } from 'lz-string';

and the piece of code that is using LZString is this:

private compressAndChangeModel(file:File){
    let reader:FileReader = new FileReader();
    reader.onload = () => {
        let compressed:string=LZString.compress(reader.result);
        this.modelChange.next(compressed);
    };
    reader.onerror = (error) => {
        console.log('Error when trying to generate base64: ', error);
    };
    reader.readAsDataURL(file);
}

How is the correct way of import LZString in my webpack project?

like image 313
brevleq Avatar asked Nov 13 '17 17:11

brevleq


1 Answers

LZString doesn't export a property called LZString. You could use a synthetic default import, import LZString from 'lz-string';.

However, compress is exported, so you can just use import { compress } from 'lz-string' and just use compress().

If you don't like the generic compress name you can also alias it using import { compress as lzStringCompress } from 'lz-string'; instead.

like image 191
Explosion Pills Avatar answered Sep 27 '22 20:09

Explosion Pills