[SalesForce] Issue with loading/using external javascript static resource in Lightning component when Locker service is Enabled

My requirement is to zip the content in client side controller using javascript library JSZIP, i have included it as a static resource. Below is the code.

Component:

<aura:component >

    <ltng:require scripts="/resource/jszip" afterScriptsLoaded="{!c.onPress}"/>

</aura:component>

Controller:

({
    onPress : function(component) {
        var packageXml = '<?xml version="1.0" encoding="UTF-8"?>' + 
            '<Package xmlns="http://soap.sforce.com/2006/04/metadata">' +
            '<version>35.0</version>' +
            '</Package>' ;

        var zipFile = new JSZip();
        zipFile.file('package.xml',packageXml,{base64: 'true'});
        var data = zipFile.generate();
        alert(data);
    }
})

I click on Press button, while locker service is enabled I am facing issue and when Locker service disabled the alert is showed as expected (attached the outputs).

Locker service enabled:
enter image description here

Locker service disabled:
enter image description here
How to make this work when locker service is enabled. Thank you for help.

The error is very cryptic and not helpful

enter image description here

Best Answer

You just forgotten to declare the variable zipFile, change the line

zipFile = new JSZip();

to this line:

var zipFile = new JSZip();

also I will recommend you to use the Salesforce Lightning CLI to check this kind of issues, its a heroku command line tool that check for this errors.

Follow this steps to install Salesforce Lightning CLI: https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/cli_intro.htm


UPDATE: In my personal org I tested the code you provided with a few modifications in an aura application and it worked fine. Here is the code:

App:

<aura:application >
    <ltng:require scripts="/resource/jszip/jszip.min.js" afterScriptsLoaded="{!c.onPress}"/>
</aura:application>

Js controller:

  ({
        onPress : function(component) {
            var packageXml = '<?xml version="1.0" encoding="UTF-8"?>' + 
                '<Package xmlns="http://soap.sforce.com/2006/04/metadata">' +
                '<version>35.0</version>' +
                '</Package>' ;

            var zipFile = new JSZip();
            zipFile.file('package.xml',packageXml,{base64: 'true'});
            var data = zipFile.generateAsync();
            alert(data);
        }
    })

I downloaded the last version (3.0.0) of jszip from their site and had the issue that the method generate() is deprecated, so I changed it to generateAsync() as is suggested in the upgrade guide.

Related Topic