问题
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
回答1:
Actually just figured it out. I needed to delcare the variable in order for typescript to use it:
declare var saveAs:any;
回答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);
回答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.
来源:https://stackoverflow.com/questions/40978750/angular2-filesaver-js