ebhh2001
ebhh2001

Reputation: 2116

How to use external library in a Typescript 2.0 project?

I have a Typescript 2.0 project that uses Common JS modules and System JS loader. I use Visual Studio code as IDE. I am having trouble using an external library (filesaver JS) in my project.

I installed both the library and the type definition via npm. Both appear in my node_modules and node_module/@types respectively.

How do I reference (import) the filesaver saveAs function in my TypeScript code in my function that is to save a blob (an object converted to a JSON string)?

I tried several variations of import, but none of them seems to work for me. I get either 'index.d.ts' is not a module error, or 'module not found' error.

Here is what I tried:

import filesaver = require('FileSaver'); //error: index.d.ts is not a module import {FileSaver} from 'file-saver'; //error: cannot find module file-saver

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "declaration": false,
    "removeComments": true,
    "noLib": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": ["es6", "es2015", "dom"],
    "sourceMap": true,
    "pretty": true,
    "allowUnreachableCode": false,
    "allowUnusedLabels": false,
    "noImplicitAny": true,
    "noImplicitReturns": true,
    "noImplicitUseStrict": false,
    "noFallthroughCasesInSwitch": true,
    "typeRoots": [
      "./node_modules/@types",
      "./node_modules"
    ],
    "types": [
      "node"
    ]
  },
  "exclude": [
    "node_modules",
    "dist",
    "src"
  ],
  "compileOnSave": false
}

Upvotes: 1

Views: 1269

Answers (2)

Stefan Ocke
Stefan Ocke

Reputation: 249

I had the same issue in an Angular 2 project that uses System JS module loader. For me

import {saveAs} from 'file-saver';

worked, but only after I explicitely set the module format of file-saver to cjs in the System JS configuration:

"packages":{
     "file-saver":{
          "main":"FileSaver.js", 
          "format": "cjs"
     }
}

As far as I understand SystemJS will recognize file-saver as AMD module by default. Maybe there is something wrong with the AMD module definition in file-saver, but I have not a very deep understanding of this. (See also https://github.com/eligrey/FileSaver.js/blob/master/FileSaver.js#L182)

Upvotes: 2

ebhh2001
ebhh2001

Reputation: 2116

This is probably not the perfect solution, but the following three lines work for me in IE 11 and Chrome.

var saveAs = require('file-saver');
var blob = new Blob([JSON.stringify(myDataObject)], { type: 'text/plain;charset=utf-8' });
saveAs(blob, "file.txt");

Upvotes: 0

Related Questions