I'm trying to use the xlsx.js library of cdnjs in a Lightning component. (https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/xlsx.js). I downloaded the js file and addit as an static resource but in the code when I try to use the XLSX object, always get an "undefined" error.
The resource always has the text/plain MIME Type, so I don't know if the problem is that SF cannot detect that is a java script file.
for the component I'm using the next syntaxis to get the file:
<ltng:require scripts="/resource/JsLibXlsx"
afterScriptsLoaded="{!c.jsLoaded}"/>
in the controller just for verify the process I have this:
jsLoaded: function(component, event, helper) {
alert('versiĆ³n 7');
try{
var xls = new XLSX();
alert(xls);
}
catch(ex){
alert(ex);
}
}
alert shows
Thanks.
Best Answer
So, to make your XSLX library work, several things need to be done:
var XLSX = {};
(for me it was 5th line), add this line of code:
window.XLSX = XLSX;
<ltng:require scripts="{!$Resource.XLSX"}/>
Library variable will be available in controller methods as XLSX. E.g.
Explanation: by default, XLSX library inside the XLSX.js file is simply referenced as:
var XLSX = {};
In ordinary js this would be considered as a global variable, but lightning locker service encloses each library in a Proxy object, so that the library lives in it's own context. However, proxy object leaves direct references to window global context, if there were any. We simply explicitly order locker service to leave a reference to XLSX object in global window context for us.
Source: experience.
Additions: standard XLSX.js library doesn't include gzip library. So if you are not going to add it separately, you should modify and use xlsx.full.min.js. Basically, you should do the same thing as was described before, but for minified version of the library.