What are the steps for integrating and expanding a JavaScript library using rollup, TypeScript, and Angular 2?

I am currently working on a project called angular2-google-maps-test and I am interested in integrating and expanding upon the JS library found at js-marker-clusterer

npm install --save js-marker-clusterer

It seems that this library is not structured as a module.

function MarkerClusterer(map, opt_markers, opt_options) {
  // MarkerClusterer implements google.maps.OverlayView interface. We use the
  // extend function to extend MarkerClusterer with google.maps.OverlayView
  // because it might not always be available when the code is defined so we
  // look for it at the last possible moment. If it doesn't exist now then
  // there is no point going ahead :)
  this.extend(MarkerClusterer, google.maps.OverlayView);
  this.map_ = map;
...

}
window['MarkerClusterer'] = MarkerClusterer;

My goal is to achieve something similar to this:

// js-marker-clusterer.d.ts file
declare module "js-marker-clusterer" {
  export class MarkerClusterer {
    constructor(map: any, opt_markers?: any, opt_options?: any);
    map_: any;
    markers_: any[];
    clusters_: any[];
    ready_: boolean;
    addMarkers(markers: any[], opt_nodraw: boolean) : void;
    removeMarker(marker: any, opt_nodraw: boolean) : boolean;
    removeMarkers(markers: any[], opt_nodraw: boolean) : boolean;
  }
}

Then, I plan to extend that class in TypeScript

/// <reference path="./js-marker-clusterer.d.ts" />
export class MyMarkerClusterer extends MarkerClusterer {
  constructor(map: any, opt_markers?: any, opt_options?: any) {
    super(map, opt_markers, opt_options);
  }   
}

However, when using rollupjs, I keep encountering this error:

[21:20:47]  bundle failed: 'MarkerClusterer' is not exported by node_modules/js-marker-clusterer/src/markerclusterer.js  MEM: 469.6MB
            (imported by src/angular2-marker-clusterer/my-marker-clusterer.ts). For help fixing this 
            error see https://github.com/rollup/rollup/wiki/Troubleshooting#name-is-not-exported-by-module

My assumption is that I need to make modifications to the rollup.config.js file, but my attempts to add it as a plugin have been unsuccessful.

  /**
   * plugins: Array of plugin objects, or a single plugin object.
   * See https://github.com/rollup/rollup/wiki/Plugins for more info.
   */
  plugins: [
    builtins(),
    //commonjs(),
    commonjs({
      namedExports: {
        'node_modules/angular2-google-maps/core/index.js': ['AgmCoreModule'],
        'node_modules/js-marker-clusterer/src/markerclusterer.js': ['MarkerClusterer']
      }
    }),

Answer №1

Honestly, I'm not too familiar with Typescript, but instead of using the commonjs plugin, you might want to consider giving the rollup-plugin-legacy a shot.

legacy({
    'node_modules/js-marker-clusterer/src/markerclusterer.js': 'MarkerClusterer'
})

Don't forget to adjust the import statement accordingly.

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

Error: The Turborepo package restricts the use of import statements outside of modules

I created a typescript "test" package in turborepo, which imports and exports typescript functions. Due to being in turborepo, it gets copied to node_modules/test. When attempting to run import {func} from "test", an error is thrown: SyntaxError: Cannot ...

TypeORM does not have the capability to specify the database setting within the entity decorator

As my TypeORM project grows in size and its components become more discreet yet interconnected, I am exploring ways to separate it into multiple databases while maintaining cross-database relations. To achieve this, I have been experimenting with the data ...

Analyze the information presented in an HTML table and determine the correct response in a Q&A quiz application

I need to compare each row with a specific row and highlight the border accordingly: <table *ngFor="let Question from Questions| paginate: { itemsPerPage: 1, currentPage: p }"> <tr><td>emp.question</td></tr> <tr> ...

Submitting an array of objects via HTTP PUT

Struggling to find a way to update a list of Objects on MongoDB in one method call within the Submit button. Spent all day yesterday attempting, but it seems to be unsuccessful. The goal is to update all product sells in the database by entering values for ...

Learn how to enhance a Vue component by adding extra properties while having Typescript support in Vue 3

Attempting to enhance a Vue component from PrimeVue, I aim to introduce extra props while preserving the original components' typings and merging them with my new props. For example, when dealing with the Button component that requires "label" to be ...

What is the reason behind tsc disregarding the include and exclude options in tsconfig.json?

I am facing an issue with my tsconfig.json file: { "compilerOptions": { "target": "ES6", "lib": [ "DOM", "ES6" ] }, "include": [ "src/server/**/*&q ...

How can you prevent the keys from being read-only when mapping onto a type?

Here's a common query: How can I change keys from readonly to writable when using a type that is Readonly? For example: type Foo = Readonly<{ foo: number bar: number }> type Bar = /* What's the method to duplicate the Foo type, but w ...

Utilizing Angular signals to facilitate data sharing among child components

I have a main component X with two sub-components Y and Z. I am experimenting with signals in Angular 17. My query is how can I pass the value of a signal from sub-component Y to sub-component Z? I have attempted the following approach which works initial ...

Error TS5083: Unable to locate the file node_modules/gts/tsconfig-google.json while setting up Angular CLI on MacOS

I encountered issues while trying to install Angular CLI on my Mac using sudo npm install -g @angular/cli. The latest error message I received is as follows: npm WARN deprecated @npmcli/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cf ...

The input element's value property updates only once

Whenever I input a number greater than 1 into the input field, the value automatically changes to 1 due to validation. Oddly enough, this only seems to work for the first number entered. For example, if I type in 11, the input value remains as it is instea ...

Access denied: Unable to rename directory '/usr/local/lib/node_modules/expo-cli' due to permission restrictions

After encountering an error that appeared to be related to permissions, I spent some time troubleshooting and finally found a solution. I wanted to share it here in case it can help others facing the same issue. If anyone has alternative solutions, please ...

Utilizing Angular's primeng library with CommonJS or AMD dependencies may lead to optimization setbacks

I recently updated my Angular app and started using PrimeNG components. However, after the update to Angular 10, I've been encountering a Warning message: CommonJS or AMD dependencies can cause optimization bailouts. This warning appears for variou ...

A practical guide to effectively mocking named exports in Jest using Typescript

Attempting to Jest mock the UserService. Here is a snippet of the service: // UserService.ts export const create = async body => { ... save data to database ... } export const getById = async id => { ... retrieve user from database ... } The ...

Using TypeScript for Type Inference in Fetch Operations

I created a custom Fetch wrapper in Typescript to fetch data from my API. I am facing an issue where the retrieved data is of type "any" and I want to convert it to a specific type, like "user". Here is the link to my codesandbox for reference: https://co ...

Retrieve the additional navigation information using Angular's `getCurrentNavigation()

I need to pass data along with the route from one component to another and retrieve it in the other component's constructor: Passing data: this.router.navigate(['/coaches/list'], { state: { updateMessage: this.processMessage }, ...

What is the best way to set a JSON string as a variable?

I am attempting to send form input data to a REST service. Currently, the format is as follows: { "locationname":"test", "locationtype":"test", "address":"test" } However, the service is only accepting the following format: { "value": "{ loca ...

The Angular EventEmitter does not broadcast any modifications made to an array

Below is the code snippet: notes.service.ts private notes: Array<Note> = []; notesChanged = new EventEmitter<Note[]>(); getNotes() { this.getData(); console.log('getNotes()', this.notes); ...

Troubleshooting problem with Webpack and TypeScript (ts-loader)

Seeking help to configure SolidJS with Webpack and ts-loader. Encountering an issue with return functions. What specific settings are needed in the loader to resolve this problem? import { render } from "solid-js/web"; const App = () => { ...

Having trouble retrieving values from Promise.allSettled on Node.js 12 using TypeScript version 3.8.3

Currently, I am delving into NodeJs 12 and exploring the Promise.allSettled() function along with its application. The code snippet that I have crafted allows me to display the status in the console, but there seems to be a hitch when attempting to print t ...

Angular - A simple way to conceal a specific row in a mat-table using Angular

I am looking to dynamically hide or show a specific column in a table by clicking on a button. The goal is to hide or delete the weight column when the "hide weight" button is clicked, and then show the weight column when the "show weight" button is clicke ...