Angular2 FileSaver.js
Solution 1
Actually just figured it out. I needed to delcare the variable in order for typescript to use it:
declare var saveAs:any;
Solution 2
Since there aren't any typings for FileSaver, I used the following approach.
For Typescript 1.8 you can import using
- Downloaded FileSaver.js from below link and saved in my project directory.
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);
Solution 3
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.
Bhetzie
Updated on June 08, 2022Comments
-
Bhetzie almost 2 years
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
-
Bhetzie over 7 yearsI tried doing this, but getting the error mentioned above h.saveAs is not a function