gamelover42
gamelover42

Reputation: 375

Angular2 FileSaver.js - Cannot find module 'file-saver'

I am working on moving an angular 1.x site to a new angular 2.0 site I created the site using angular-cli 1.0.0-beta.15.

I have a button to export some data to a CSV file. When the page first loads I get an error message "Cannot find module 'file-saver'", but when I click the button everything works perfectly.

I have the FileSaver.js component installed:

package.json

...
"dependencies": {
  ...
  "@types/filesaver": "0.0.30",
  "file-saver": "^1.3.2"
  ...
}
...

in my export.service.ts:

import { saveAs } from 'file-saver';
...
let file = new Blob(['hello world'], { type: 'text/csv;charset=utf-8' });
saveAs(file, 'helloworld.csv');
...

Does anyone know how to resolve this error?

Upvotes: 14

Views: 43763

Answers (7)

Allaraj
Allaraj

Reputation: 1

I am using Angular 16 and in my case, the solution was to install:

npm i --save-dev @types/file-saver --legacy-peer-deps

and if needed, this as well:

npm install file-saver --save --legacy-peer-deps

Upvotes: 0

Prasool
Prasool

Reputation: 51

This is an old post but incase you have this error while upgrading to angular 10, change import statement to,

import { saveAs } from 'file-saver';

old import,

import { saveAs } from 'file-saver/FileSaver';

Upvotes: 1

Juan Rojas
Juan Rojas

Reputation: 8861

Install npm @types package

npm i --save-dev @types/file-saver

from https://stackoverflow.com/a/39261890/403999

@types is the new way to install the definitions in typescript 2.0

Upvotes: 2

Parinda Rajapaksha
Parinda Rajapaksha

Reputation: 3117

Install the Library as follows,

npm install file-saver --save

This will solve your problem.

Upvotes: 5

Andre Passos
Andre Passos

Reputation: 189

just use this import statment

import * as fileSaver from 'file-saver';

Upvotes: 18

YairTawil
YairTawil

Reputation: 4111

On angular-cli you should:

1) install the library to your node_modules:

npm i -S file-saver

2) add reference of js file on 'scripts' in angular-cli.json file:

"scripts": ["../node_modules/file-saver/FileSaver.js"]

3) on your typings.d.ts file :

declare function saveAs();

after that you can use saveAs() everywhere you need example:

export class MyClass{
  constructor(){
    saveAs(blablabla...)
  }
}

Good Luck!

Upvotes: 3

Gregor Biswanger
Gregor Biswanger

Reputation: 557

Install the new TypeScript 2 version.. that should work..

Upvotes: -3

Related Questions