Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Import for filesaver.js

I am new to using the import function in Javascript and am mystified by the instruction on how to install filesaver.js.

In my code I have:

<script src="/scripts/FileSaver.js"></script>

<script>
    import { saveAs } from 'file-saver/FileSaver';
    $("#xmlToFile").click(function() {
            var xml = $("#jobXml").val();
            var blob = new Blob([xml], { type: 'text/xml' });
            var filename = $("#Job_JobID").val();
            saveAs(blob, filename + ".txt");
        });
</script>

but Chrome chokes on the import line with Unexpected Token {

What am I doing wrong ?

like image 531
Lobsterpants Avatar asked Dec 16 '25 11:12

Lobsterpants


1 Answers

The module appears to be designed for projects which use WebPack and Babel, but you are trying to load it directly into the browser without transpiling it.

Their wiki has an example showing how to use a version that is pre-transpiled for browsers:

<script src="http://cdn.jsdelivr.net/g/filesaver.js"></script>
<script>
      function SaveAsFile(t,f,m) {
            try {
                var b = new Blob([t],{type:m});
                saveAs(b, f);
            } catch (e) {
                window.open("data:"+m+"," + encodeURIComponent(t), '_blank','');
            }
        }

SaveAsFile("text","filename.txt","text/plain;charset=utf-8");

</script>
like image 181
Quentin Avatar answered Dec 19 '25 02:12

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!