I'm using FileSaver.js with angular 2 and it works pretty well; however, I'm getting a semantic error in my build:
error TS2304: Cannot find name 'saveAs'
I'm using the angular 2 seed and added the library to my project.config like this:
this.NPM_DEPENDENCIES = [
...this.NPM_DEPENDENCIES,
{src: 'file-saver/FileSaver.min.js', inject: true},
];
this.SYSTEM_CONFIG_DEV.paths['file-saver'] =
`${this.APP_BASE}node_modules/file-saver/FileSaver`;
this.SYSTEM_BUILDER_CONFIG.packages['file-saver'] = {
main: 'FileSaver.js',
defaultExtension : 'js'
};
I can use saveAs in my component:
downloadFile(data: any){
var blob = new Blob([data], { type: 'text/csv' });
//saveAs is a function in the FileSaver.js library https://github.com/eligrey/FileSaver.js
saveAs(blob, "results.csv");
}
The problem is that the semantic error causes my build to fail when pushed to my cloud environment.
I've tried adding the typing via:
npm i @types/file-saver
This allows me to import:
import { saveAs } from 'file-saver';
However, this gives me the error:
h.saveAs is not a function
FileSaver. js. FileSaver. js is the solution to saving files on the client-side, and is perfect for web apps that generates files on the client, However if the file is coming from the server we recommend you to first try to use Content-Disposition attachment response header as it has more cross-browser compatiblity.
Angular File Saver is an AngularJS service that leverages FileSaver.js and Blob.js to implement the HTML5 W3C saveAs() interface in browsers that do not natively support it.
Learn how to create a saveAs function to download one or multiple files in JavaScript. updated on November 21, 2021 November 14, 2021 By Muhi Masri. In the web world, saving a file or “Save As” means downloading a file to the client's machine. There isn't a built-in method in JavaScript that allows us to do so.
Actually just figured it out. I needed to delcare the variable in order for typescript to use it:
declare var saveAs:any;
Since there aren't any typings for FileSaver, I used the following approach.
For Typescript 1.8 you can import using
https://github.com/eligrey/FileSaver.js/blob/master/FileSaver.js
2.Then in component I wanted to use FileSaver, I loaded the saved FileSaver.js and assigned a reference to it using
let fileSaver = require('../../assets/js/FileSaver');
Right after my imports.
Now anywhere i wanted to save the file using FileSaver, I would to call it using
fileSaver.saveAs(blob, fileName);
However, for Typescript 2.x you can import using
import * as filesaver from '../../assets/js/FileSaver';
and use it as:
fileSaver.saveAs(blob, fileName);
Other solution would be to install FileSaver type package
npm install --save @types/filesaver
Since TSConfig is by default looking in the directory @types/* for types, it will be automatically recognized in your whole code/application.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With