Tips for initializing Cytoscape using Typescript

I developed a React component using Typescript that utilizes cytoscape (along with its typings) as a headless model. My goal is to turn this into an NPM package so it can be easily imported into other projects.

About my library:

  1. It functions correctly when I import cytoscape.js in my index.html as a static asset
  2. However, it fails when I try to npm install my component in a new ES6 app:
    Uncaught ReferenceError: cytoscape is not defined at new WbsLayout
    . This issue arises even though cytoscape gets automatically installed in node_modules when installing my component.

Typescript Source Code

WbsLayout.tsx:

export class WbsLayout  {
    //...
    public cy: Cy.Core;
    constructor(graph: any, Options?: Options) {           
        this.cy = cytoscape({ // <-- Works or fails based on cases #1 and #2 mentioned above
            headless: true,
            elements: graph
        });
        //...
    }
    //...
}

It's worth noting that I do not have a

import cytoscape from 'cytoscape'
statement anywhere in my component source. This was intentional as, with Typescript and how cytoscape's typings are set up, I found it unnecessary for my component to work with cytoscape imported through HTML. However, this might pose a problem for an NPN package...

Wbs.tsx:

A straightforward React component which receives the prop WbsLayout.

cytoscape's Typings (relevant excerpt only)

declare namespace Cy {
    //...
    interface Core { }

    //...
    interface Static {
        (options?: Cy.CytoscapeOptions): Core;
        (extensionName: string, foo: string, bar: any): Core;
        version: string;
    }
}

declare module "cytoscape" {
    export = cytoscape;
}
declare var cytoscape: Cy.Static;

Webpack 2 Configuration

The files Wbs.tsx, WbsLayout.tsx, and others are bundled into @nodeject/wbs-react through Webpack 2:

(*webpack configuration*)

tsconfig.json

(*tsconfig.json content*)

New ES6 App Source Code

(*ES6 app code snippet*)

Answer №1

After some troubleshooting, I discovered that removing cytoscape from the externals in webpack solved the issue I was facing. The necessary changes to make it work were:

"cytoscape": {
  root: 'Cy',
  commonjs2: 'cytoscape',
  commonjs: 'cytoscape',
  amd: 'cytoscape'
 }

The correct configuration should be:

"cytoscape": {
  root: 'cytoscape', <--------
  commonjs2: 'cytoscape',
  commonjs: 'cytoscape',
  amd: 'cytoscape'
 }

Answer №2

Did you attempt to bring it in as ..

const cytoscape = require('cytoscape');

If so, could you share your tsconfig.json too?

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

Prevent duplicate key errors when performing bulk insert operations with MongoDB

Is there a way to perform a bulk insert and proceed even if a duplicate key error occurs? I have a collection with a unique index on the id field (not _id) and some existing data. I need to add new data to the collection while skipping any documents that ...

Attempted to set up Shopify Slate on a Windows operating system, but unfortunately encountered issues with the installation

Having trouble installing Shopify Slate on Windows, need some assistance! npm version: 6.9.0 yarn version: 1.17.3 gulp version: CLI version: 2.2.0 Local version: 4.0.2 Here's how I try to install it: npm install -g @shopify/slate ...

The parameter type '{ email: string; }' in NGXS does not accept arguments of type 'string'

Struggling to retrieve data from an API using ngxs with this.store.dispatch(new GetUser(userEmail)) Attempted to use the user id stored in local storage as a string and convert it to a number but encountered a similar error (Argument of type 'string&a ...

Exporting Arrays in Ionic Angular with Typescript is an essential feature

When trying to access an exported component in Typescript, there may be issues with importing the module correctly into another component. An error message is displayed when calling the AddToArray method: Cannot read property 'push' of undefi ...

Raycasting in Three.js is ineffective on an object in motion

Working on a project that combines three.js and typescript, I encountered an issue while attempting to color a sphere by raycasting to it. The problem arises when the object moves - the raycast doesn't seem to acknowledge the new position of the objec ...

Error: Module not found - Imported Node Module

I have been struggling to make modifications to an npm package with little success. I have spent hours troubleshooting and would greatly appreciate some guidance. https://www.npmjs.com/package/dxf After forking the package into my Github account, I proce ...

How can I display a modal with image options and image selection using Ionic 4?

Currently, I am developing an Ionic 4 Angular application and implementing an Ionic modal feature. I would like to include images in the modal, so that when a user clicks on them, they are displayed. ...

What is the best way to ensure the correct resolution order of several promises?

Exploring the realm of modern JS and diving into ECMAScript 6 Promises. Experimenting with a simple test: let slow = new Promise((resolve) => { setTimeout(function() { console.log('slow'); resolve(); }, 2000, 'slow'); }); ...

In TypeScript, vertical bars and null are commonly used for type unions

Greetings! I am just starting to learn JavaScript and TypeScript I have a question about the code snippet below What does the pipe symbol (|) signify? Also, why is null = null being used here? let element: HTMLElement | null = null; ...

ViewChild with the focus method

This particular component I'm working on has a hidden textarea by default : <div class="action ui-g-2" (click)="toggleEditable()">edit</div> <textarea [hidden]="!whyModel.inEdition" #myname id="textBox_{{whyModel.id}}" pInputTextarea f ...

What are some ways to resolve this console error: "TS2307: Could not locate module '@components/common/ButtonBlock' or its corresponding type declarations."

While the project is running smoothly, I am noticing a multitude of errors appearing in the console of VS Code. How can I eliminate these error messages? It seems to be related to TypeScript. Additionally, I am encountering an error in the browser as well ...

Node corrupting images during upload

I've been facing an issue with corrupted images when uploading them via Next.js API routes using Formidable. When submitting a form from my React component, I'm utilizing the following functions: const fileUpload = async (file: File) => ...

The system detected an Image with the source "/images/logo.png" as the primary element contributing to Largest Contentful Paint (LCP)

I have been working on a project using Next.13 and Typescript. In order to display an Image, I created a component called Logo.tsx. "use client"; import Image from "next/image"; import { useRouter } from "next/navigation"; c ...

Angular location services

I'm experiencing some difficulties with the geolocation feature. It works fine when the user clicks allow, but there's an issue when using If else. If the user clicks deny, it doesn't insert into the else block. You can check out this DEMO f ...

Unable to publish using the "npm publish" command

I am the maintainer of the NPM package LintRoller. You can find it here: https://npmjs.org/package/lintroller Recently, I attempted to push a new version but encountered the following error: npm ERR! publish Failed PUT response undefined npm ERR! Error ...

Having trouble resolving all parameters for the SiteNotificationComponent: (?)

I encountered an issue while attempting to append a component to the DOM. The error message displayed was "Can't resolve all parameters for SiteNotificationComponent: (?).at syntaxError." My goal was to insert HTML content by invoking showNotificatio ...

Unable to persist AWS CDK ec2.Instance userData configuration

Trying to launch an ec2 instance with AWS CDK has been successful, but I am struggling to make the userData persistent so it runs on every boot. Despite searching extensively, I couldn't find any documentation on how to achieve this. The code below wo ...

What is the process for importing the Three.js Line library as an ES6 module?

My coding process involves utilizing modern JS (ES6), which includes modules. While Three.js is accessible as an ES6 module, certain components of the library - such as LineSegmentsGeometry, LineGeometry, LineSegments2, and so on - are not available in th ...

What is the result of using `X ? A : B` in typescript?

type TestAny = any extends 'a' ? 1 : 2 // => 1 | 2 why??? how to interpret? type TestUnknown = unknown extends 'a' ? 1 : 2 // => 2 type TestStringA = 'a' extends 'a' ? 1 : 2 // => 1 type SomeUnion = ' ...

Utilize the 'cheerio' npm module within your K6 test bundle

Struggling to set up tests using the K6 framework from LoadImpact? Having trouble including external NPM modules as per their documentation site instructions? You're not alone! The documentation site offers a detailed example on parsing XML from a SO ...