Utilizing an external library in a Typescript 2.0 project: A comprehensive guide

I am currently working on a Typescript 2.0 project that utilizes Common JS modules and System JS loader. My IDE of choice is Visual Studio code. I am encountering a challenge with integrating an external library (filesaver JS) into my project.

After installing both the library and the type definition via npm, I can see them in my node_modules and node_module/@types directories respectively.

My main issue arises when trying to reference (import) the filesaver saveAs function in my TypeScript code within a function that is responsible for saving a blob (an object converted to a JSON string).

Despite multiple attempts with various import options, I have not been successful. I consistently encounter errors such as 'index.d.ts' is not a module or 'module not found'.

Here are the import statements I have 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
}

Answer №1

In an Angular 2 project using System JS module loader, I encountered a similar issue.

import {saveAs} from 'file-saver';

What worked for me was explicitly setting the module format of file-saver to cjs in the System JS configuration:

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

By default, SystemJS recognizes file-saver as an AMD module. There may be an issue with the AMD module definition in file-saver, but I do not have a deep understanding of this. (Refer to https://github.com/eligrey/FileSaver.js/blob/master/FileSaver.js#L182)

Answer №2

While it may not be the most ideal resolution, the next set of code snippets have proven to be effective in both IE 11 and Chrome browsers.

const saveFile = require('file-saver');
const dataBlob = new Blob([JSON.stringify(myData)], { type: 'text/plain;charset=utf-8' });
saveFile(dataBlob, "data.txt");

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular: Simplifying complex JSON structures

Is there a built-in feature in Angular for flattening JSON data and then restructuring it back? I came across some code below, but I'm wondering if Angular offers any native library functions for this task. If not, I may consider incorporating this fu ...

Is there a way to include the request body (req.body) in the msg object using express-winston?

My current challenge involves logging {{ req.body }} using the msg: object in express-winston. Even after whitelisting the body with expressWinston.requestWhitelist.push('body');, it still does not appear in the log. export const accessLogger = ...

Observing the completion of a subscriber function

Is there a more streamlined way to determine if the subscriber has finished executing or return something and catch it up-stream? Consider the following code snippets: this._subscriptions.push(this._client .getCommandStream(this._command) // R ...

Guidelines for displaying user profile information in the dashboard page through an Angular project, considering the different user types (user, super user, admin)

In my application, I have implemented the dashboard feature. There are three types of dashboards: the regular user dashboard, super user dashboard, and admin dashboard. The super user and admin dashboards include additional tables along with the data from ...

Issues with installing the forked version of the npm/Angular 8 package differ from the original installation method

After utilizing git, forking, branching, pull requests, and npm in my standard nodejs projects without any major issues, I encountered an unexpected problem. When trying to Fork an Angular repository and integrate this forked version into my project, I not ...

Using Angular 6 to implement a select dropdown within a *ngFor loop in

My Angular 6 component fetches an observable list of users and displays a table using the *ngFor statement. Each row has a submit button that calls a function passing in the user for that row. This functionality works correctly. Now, I want to add a selec ...

Implementing TypeScript type declarations for merging core types

Is there a way to perform type declaration merging in TypeScript for built-in types when using imports? I am currently attempting to merge interfaces as per the guidelines outlined in this documentation: https://www.typescriptlang.org/docs/handbook/declar ...

What are the issues causing trouble for my modules, services, and more in Angular ^17?

As I was going through the themes, I couldn't find a similar question. My issue revolves around Angular's inability to locate modules and services that are created using "ng g". Everything seems to be correctly set up, but errors or warnings keep ...

Angular: The type '"periodic-background-sync"' cannot be assigned to type 'PermissionName'

I am trying to enable background sync, but I keep encountering an error when I try to enter the code. Why can't it be found? Do I need to update something? This is my code: if ('periodicSync' in worker) { const status = await navigato ...

Utilizing a Single Class with TypeScript in Angular and Node.js Servers: Best Practices

I've named the file containing the following code as models.ts import {BusStage} from "./busStage"; export class BusRoute { name: string; origin_direction_1: string; origin_direction_2: string; stops: number; id: string; meta ...

When using TypeScript, the reducer function may not be recognized, causing the type to display as 'any

I am a beginner in Typescript and we are implementing hooks in our React application. We have a shared thunk action creator that triggers one of the actions. appSlice.ts type ThunkOptions = { method: number, api_url: string, body: any | null } ...

React-hook-form does not display the input length in a custom React component

Introducing a custom Textarea component designed for reusability, this basic textarea includes a maxlength prop allowing users to set the maximum input length. It also displays the current input length in the format current input length/max length. While ...

Steps to resolve the issue: angular/[email protected] - unable to resolve the dependency

Encountering a challenging compiler error, I am determined to find a solution. Despite numerous attempts to install different library versions, the issue persists. It appears that the firebaseui-angular package necessitates an alternative angular/fire ver ...

Encountering an error in Angular where the property does not exist in type

Struggling to create a collapsible menu within my header component in an Angular project, I've hit a snag with proper JSON formatting. The error message that keeps popping up reads: Error: src/app/components/header/header.component.html:48:49 - error ...

How to refresh an Observable in Angular 2

Description: Presently, I am utilizing Angular2 (now updated to Angular4). In my component's constructor, I am subscribing to a service using the code: this.policyService.getBaseCommission().subscribe(response => response). The data obtained from ...

Utilizing Angular Forms for dynamic string validation with the *ngIf directive

I have a challenge where I need to hide forms in a list if they are empty. These forms contain string values. I attempted to use *ngIf but unfortunately, it did not work as expected and empty fields are still visible in the list. How can I address this iss ...

The Type '{Property: string, Property2: string} does not match the type Observable<Filters[]>

Here is a method I am trying to use: getFilters(): Observable<Filters[]> { let filters: Observable<Filters[]> = [ { property: "Value", property2: "Value2" }, { property: "Value3", property2: "V ...

Encountered an unexpected error while attempting to integrate my custom npm library "MyModule" into my Angular 2 project

I have created my own library which consists of one module and one component. After compiling my library, I add it to my main project using the following command: npm link ng-shared Next, when I attempt to import SharedModule in my module file as shown b ...

Automatically update the cart count in the header component in Angular 6 when a product is added to the cart, without the need to

I am working on an E-Commerce application using Angular 6. I am facing an issue with updating the shopping cart count in the header component whenever a product is added or removed from the cart. The cart count only updates when I refresh the page. I have ...

Listening to events on the iterative variable of NgFor directive in Angular 2

Angular2 has been my latest exploration in solving a unique data binding challenge. In my UI, I've presented a javascript array of objects like a database recordset in an HTML table. Each row contains menus and inputs allowing users to modify the rec ...