Using TypeScript syntax to define types; utilizing the export default keyword to incorporate an external JavaScript library within an Angular2

I've been attempting to incorporate a JavaScript library known as bricks.js into my project, but unfortunately, there isn't a publicly available type definition for it.

The library seems to be exporting something along these lines:

export default (config) => {
    const instance = SomeConstructorFunction(config);
    return instance;
}

I'm having trouble creating an accurate type definition (.d.ts) for this function. When I import it, tsc either compiles with undefined results or fails to compile altogether.

So far, this .d.ts definition has successfully compiled:

declare module 'bricks.js' {
    export class Bricks {
         constructor(config: any);
         pack(); // some function available on the instance
   }
}

However, when I try to import it within my AngularJs 2 component like this:

import { Bricks } from 'bricks.js';
this.bricks = new Bricks({//some config here});

The imported Bricks object turns out to be undefined, resulting in an error being thrown. It's puzzling to me how to create a proper .d.ts file for this library. Additionally, since the library is compiled using Babel, I have a feeling that Babel might be doing something with the arrow function default exports...

Answer №1

After navigating my way through this challenging situation...

I discovered that the bricks.js library utilizes ES6 modules (located in the src folder) but is also compiled using Babel.

For my Angular2 project dependencies, I opted to use Systemjs for loading,

This left me with two potential paths:

  • To utilize the ES6 bricks.js from the src folder. This involves employing modern TypeScript syntax for loading ES6 modules and configuring a transpiler in the Systemjs setup to enable proper loading of the library and its dependencies.

  • Alternatively, I could use the Babel-transpiled bricks.min.js from the dist folder. However, this requires utilizing the non-module entity syntax.

Refer to

In order to circumvent transpilation via Systemjs, I chose the latter solution.

Here's what I implemented:

.index.d.ts

declare module 'bricks.js' {
    interface Bricks {
        pack();
    }

    function bricksFactory(config:any): Bricks

    export = bricksFactory;

}

systemjs.config.js

...
var map = {
    ...
    'bricks.js':                  'node_modules/bricks.js/dist/'
    ...
}
...
var packages = {
    ...
    'bricks.js':                  { main: 'bricks.min.js', defaultExtension: 'js'}
};

my.component.ts

import bricksFactory = require('bricks.js');

this.bricksInstance =  Bricks({
    container: '.mycontainer',
    packed: 'data-packed',
    sizes: [
        { columns: 2, gutter: 10 },
        { mq: '768px', columns: 3, gutter: 25 },
        { mq: '1024px', columns: 4, gutter: 50 }
    ]
});

Answer №2

To bring in the code, simply include

import * as Blocks from 'blocks.js';

To set it up, you can create something similar to this:

declare module "Blocks" {
  function setupConfig(config): CustomFunction;
    var _temp = setupConfig;
   export = _temp;
}

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

Experimenting with viewProvider in a component test

@Component({ selector: 'app-entity-details', templateUrl: './entity-details.component.html', styleUrls: ['./entity-details.component.scss'], viewProviders: [{ provide: ControlContainer, useFactory: (container: ...

Modifying a variable within an arrow function does not result in the variable being changed when checked outside of the arrow

I am currently developing an application with Angular and Typescript where I need to update the value of a variable inside a function. To retrieve the data required, I'm utilizing a service. Below is the code snippet for reference: let isDataAvailab ...

Exploring Angular's nested categories with the power of *ngFor loop

I am facing a challenge with an undefined number of arrays that can be nested without limit. This is for the "filtering" section on a page where products are listed. However, I am struggling to dynamically create this structure on the HTML side. [ { ...

Guide on retrieving specific values within an array and mapping them to separate arrays using the HttpClient service in Angular 7+

I'm having a tough time grasping the concept of handling data once it's returned from an Http Request in Angular 7+ The Service responsible for fetching each location is shown below: import { Injectable } from '@angular/core'; import ...

I am unable to simply import lodash.add into my Angular 4 project

I'm struggling to import the add method from the lodash library using Angular 4 and TypeScript. I've attempted various approaches: import { add } from 'lodash'; import { add } from 'lodash/add'; import * as add from 'l ...

Next.js does not support tooltips with custom children components

I created a unique Tooltip component and I'm attempting to include NextLink as the children. However, I encountered an error similar to the one below. Warning: Failed prop type: Invalid prop `children` supplied to `ForwardRef(Tooltip)`. Expected an e ...

How to display a JSON object array in Angular 4

My object is made up of fields, objects, and arrays, resembling the following structure: Within my HTML code, I retrieve data for aaType and adjust. <div class="flexdirectioncolumn"> <div class="flex50"> <label class="label-pro ...

Encountering TypeScript errors with React-Apollo when using GraphQL to pass props to a higher order component

I've encountered some challenges while attempting to link a React class component with my local Apollo cache data. Following the guidelines outlined here, I have run into issues where VSCode and Webpack are generating errors when I try to access data ...

What is the reasoning behind browserify intervening in the gulp build process to compile my TypeScript code for web workers?

I'm currently working on setting up a web worker in a React/Typescript project that utilizes Gulp with Browserify for the build process. This task has proven to be quite challenging. The issue I'm facing right now is that during the typescript co ...

Enhancing external access

I am currently working on enhancing the types of convict. The current definitions export convict using the following: namespace convict { ... } interface convict { ... } declare var convict: convict; export = convict; To augment the interface, I have mad ...

Angular - Ensuring the Independence of Field Pairs During Validation

I need to independently validate two sets of fields. One set is for passwords, which should match each other. The second set is for email addresses, which should also match. The current method I have tried isn't working. Can someone guide me on how ...

How to Create Angular 2 Material Tabs with Dual Labels

How can I create a double label for Material Tabs? I tried customizing the label like this: <ng-template mat-tab-label> <div>{{mainTab.label}}</div> <div>{{mainTab.label}}</div> < ...

Running unit tests using Typescript (excluding AngularJs) can be accomplished by incorporating Jasmine and Webpack

While there is an abundance of resources on how to unit test with Webpack and Jasmine for Angular projects, I am working on a project that utilizes 'plain' TypeScript instead of AngularJs. I have TypeScript classes in my project but do not use c ...

Having trouble with npm i after installing the newest versions of node and npm

I recently upgraded my node and npm to the latest versions. However, my ionic 3 project (version 3.9.2) is now encountering issues when I run npm i. Strangely, this problem only occurs with this specific project and not with new projects. Any help in resol ...

Ways to modify the access control to permit origin on a specific API URL in React

https://i.stack.imgur.com/tqQwO.png Is there a way to modify the access control allow origin for a URL API? I keep encountering error 500 whenever I try to load the page. After logging in, I included this code snippet: const options = { header ...

What is the most effective way to retrieve cursors from individual entities in a Google Cloud Datastore query?

I am currently working on integrating Google Cloud Datastore into my NodeJS application. One issue I have encountered is that when making a query, only the end cursor is returned by default, rather than the cursor for each entity in the response. For insta ...

The type FormGroup<any> lacks the controls and registerControl properties compared to AbstractControl<any>

I've been developing a reactive nested form inspired by this YouTube tutorial - https://www.youtube.com/watch?v=DEuTcG8DxUI Overall, everything is working fine, except for the following error - https://i.sstatic.net/bZHPV.png Below are my files. ho ...

I encountered an issue with my TypeScript function in Angular, as it is unable to process multiple uploaded files

I'm having trouble with my TypeScript function in Angular that is unable to read multiple uploaded files. fileUpload(event: Event) { const self = this; this.imageUploadInp = event.target as HTMLInputElement; this.imageUploadInp.addEventLis ...

ngx-emoji-mart customBackgroundImage directive

Currently, I am integrating ngx-emoji-mart with Angular 6 and encountering an issue with the backgroundImageFn directive. The ngx-emoji-mart documentation suggests using the directive to load the emoji sheet locally like this: <emoji-mart [backgroundIm ...

What is the best way to submit form data along with an image using Angular?

Recently, I built an application where users can submit form data along with an uploaded image. Since I am new to Angular, I am facing some challenges in merging the user-submitted data model and the image upload using the FormData method. Can anyone guide ...