Angular2 FileSaver.js

Bhetzie picture Bhetzie · Dec 5, 2016 · Viewed 11.4k times · Source

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

Answer

Bhetzie picture Bhetzie · Dec 5, 2016

Actually just figured it out. I needed to delcare the variable in order for typescript to use it:

declare var saveAs:any;