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

Applying REGEX on input text in React Native

I'm having trouble getting my regex function to work correctly, so I believe there might be an error in my code. Any assistance would be greatly appreciated. Here is the regex function I am using: let validatePlate = (plate) => { var re = /(^[A ...

How to duplicate a file without removing the original in node.js

I'm in need of a node.js method that can copy, move, and rename a file from one location to another without removing the original. I've come across other options like fs.rename but they seem to delete the original file. This process will be exec ...

Error detected when running yarn build command due to syntax issue

Error message encountered while running Electron Build: SyntaxError - Unexpected token function $ build ...\node_modules\read-config-file\out\main.js:72 async function readConfig(configFile) { ^^^^^^^^ SyntaxError: Unexpected to ...

What is the process of invoking a service from a controller?

In my MovieSearchCtrl controller class, I have a method called returnMovies(query) that looks like this: returnMovies(query): any { return MovieSeat.MovieSearchService.getMovies(query); } Within the MovieSearchService service class, there is a functi ...

How can I configure nest.js to route all requests to index.html in an Angular application?

I am developing an Angular and NestJS application, and my goal is to serve the index.html file for all routes. Main.ts File: async function bootstrap() { const app = await NestFactory.create(AppModule); app.useStaticAssets(join(__dirname, '..&ap ...

Error message: When attempting to perform a basic npm install on Codeship, an SSL error occurred due to an un

Encountering a persistent problem with my Codeship Basic setup step failing during the execution of npm install: npm http GET https://registry.npmjs.org/babel-runtime npm ERR! Error: SSL Error: CERT_UNTRUSTED npm ERR! at ClientRequest.<anonymous> ...

What is the method for executing a specific task using grunt.registerTask()?

My grunt tasks are registered like this - grunt.registerTask('regenerateSources', ['clean:local', 'bower', 'uglify']); When I run grunt regenerateSources, it executes the clean, bower and uglify tasks. But is there ...

Is it possible to showcase a unique date for every item that gets added to a list?

I am new to using React, so please bear with me. I want to be able to show the date and time of each item that I add to my list (showing when it was added). I am struggling to get this functionality working with my current code. Any help or explanation o ...

Avoid accessing members in Vue 3 using TypeScript that may be unsafe

Recently, we initiated the process of upgrading from Quasar v1 to Quasar v2 (moving from Vue 2 to Vue 3). In the past, this code functioned without any issues: // src/pages/myComponent.vue <script lang="ts"> import { defineComponent } from ...

TypeScript: defining a custom type with a collection of properties following a consistent pattern

I am looking for a way to create a type that can accommodate any number of properties following a predefined pattern, like so: type Values = { id: number; id1?: number; id2?: number; id3?: number; // ... somethingElse: string; anotherOne: num ...

What is the method for substituting one text with another using two-way data binding?

I implemented two different cases in my Mat-Table. When there is no data, the user will see a message saying "No Data Found". However, if the user enters text in the filter search, the "No Data Found" message should be hidden and replaced with the entered ...

Javascript - Single line conditional statement

As I continue to improve my JavaScript skills, I'm looking for guidance on optimizing the following if statement. Is there a way to shorten it, possibly even condense it into one line? How can I achieve that? onSelect: function (sortOption) { th ...

NextJS-created calendar does not begin on the correct day

I'm facing an issue with my calendar code where it starts rendering on a Wednesday instead of a Monday. I want to adjust the layout so that it always begins on a Monday by adding some empty boxes at the start of the calendar. Essentially, I need to s ...

Facing issues while trying to deploy my Angular 5 application on Heroku

I've encountered an issue while attempting to deploy my Angular 5 project on Heroku. While I've successfully deployed other projects before, this one seems to have a dependency problem that is hindering the process. Locally, running ng build pos ...

Performing unit testing on a Vue component that relies on external dependencies

Currently, I am in the process of testing my SiWizard component, which relies on external dependencies from the syncfusion library. The component imports various modules from this library. SiWizard.vue Imports import SiFooter from "@/components/subCompon ...

What are the steps to run a webpack project without relying on webpack-dev-server?

I've been working on hosting my project on GitHub pages by creating a /doc file and placing all my HTML, CSS, and JS there. If you're interested, you can check out my project here: https://github.com/mattfrancis888/the_movie_db The only way I&a ...

Execute the npm command to organize the files in case the specified directory does

I am facing an issue with my npm package.json script that needs to be executed only when the dist folder is not present. Here is the snippet from my package.json: "scripts": { "predev": "! test dist && webpack --config=webpack.dll.config.js } ...

Performing several HTTP requests in a for loop in Angular 8

Within the backend, there exists an endless list of cars. Each car is designated by a unique id and has a corresponding model name. I possess a compilation of car IDs, as illustrated below: const carIds = ['abc','xyz']; My objective ...

Using AngularJS with CDN: A beginner's guide

If I need to create an app using AngularJS with Cordova in Visual Studio, do I need anything else besides the Google CDN for AngularJS? <!doctype html> <html ng-app> <head> <title>My Angular App</title> <script s ...

Tips for applying personalized CSS to individual Toast notifications in Angular

MY QUESTION : I am looking to customize the CSS of a single toast used in Angular components. While there may be multiple toasts, I specifically want to style one particular toast differently. For example, the toast image can be viewed here: example toast ...