I need to use the FileSaver.js (https://github.com/eligrey/FileSaver.js/) in my Angular2 application.
I know I can add it as a script file in main html page and it will work. But I was wondering what would be the best approach in case of an Angular 2 (TypeScript) application so that I can just call window.saveAs to save file.
Just doing
npm install file-saver --save
is a good start. You also need a typescript declaration file (likefile-saver.d.ts
ortypings.d.ts
) for this library is in plain javascript. Normally you would get it by doingnpm install @types/file-saver
but this package is currently outdated.I have created a file-saver.d.ts for myself – just place it in your source directory.
file-saver.d.ts
Then you can use saveAs as follows:
your.ts
Of course, don't forget to update your loader's configuration.
For SystemJS you need something like this:
I managed to get it work using this approach (Angular-CLI):
After that import Filesaver in component:
And you can use it like this:
As you can see, you don't have to add anything in angular-cli.json. Just install library and it's types, import it and you are ready to go.
If you're using Angular-CLI to build your project, you can install it by running
Since there aren't any typings for FileSaver, I had to do:
in my
typings.d.ts
file.Then, to use it:
For reference, these steps are taken from Angular-Cli's steps for installing third-party libraries
Edit 9/27/2017: It appears there is now a type definition for FileSaver.js according to the README instructions, so instead of the
you just need to