Extending a Svelte component with a P5JS class: A step-by-step guide

As a newcomer to SO, I haven't asked many questions before, so please bear with me if I don't entirely follow the guidelines. I'll do my best to explain the issue at hand.

In my project, I am utilizing Sveltekit (create-svelte) and P5JS (p5-svelte) to develop a canvas along with a user interface to manage parameters of the P5JS sketch. My goal is to create a class (Node) that extends a class from P5JS (Vector).

While I successfully import the Vector type from p5 without any issues, I'm unsure how to import Vector as a module. The crux of the problem arises when attempting to extend the Vector class, resulting in an error:

<script lang="ts"\>
    import P5 from "p5-svelte";
    import type { Sketch } from "p5-svelte";

    import type { Vector } from "p5"; // Importing the Vector type from p5 - everything functions well since @types/p5 is installed
    
    // import { Vector } from "p5"; // This method doesn't work: "Internal server error: Failed to resolve import "p5" from "src/routes/+page.svelte". Does the file exist?"
    
    // import { Vector as p5Vector } from "p5"; // Same error message as above.
    
    let width = 55;
    let height = 55;
    
    const sketch: Sketch = (p5) => {
        p5.setup = () => {
            p5.createCanvas(400, 400);
            const myVector: Vector = p5.createVector(100, 100); // Successful creation of vector
            console.log(myVector.x); // Outputs 100
        };
    
        p5.draw = () => {
            p5.ellipse(p5.width / 2, p5.height / 2, width, height);
        };
    };
    
    // Here lies the problem. Class Node fails to work, displaying "ReferenceError: Vector is not defined". Even importing Vector as a type triggers an error stating "'Vector' cannot be used as a value because it was imported using 'import type'.ts(1361)". Using p5.Vector also proves ineffective.
    class Node extends Vector {
        constructor(x, y) {
            super(x, y);
            this.x = x;
            this.y = y;
        }
    }

\</script\> …

(for full file, see +page.svelte)

In addition, including p5 as a dev dependency alongside this setup results in an error even upon simply importing the library (Error 500 "window not defined").

I must be overlooking something obvious here.

The complete example can be found on GitHub and deployed here (leading to an Error 500, unfortunately).

Answer №1

If you are looking to extend a runtime type (such as a class), using the type package may not be helpful. Instead, consider the following approach:

import p5 from 'p5';

class Node extends p5.Vector { ... }

While the type package can provide information on the structure of p5.Vector, the actual value needs to come from the p5 library itself.

The error message regarding "window not defined" typically indicates that the package is not compatible with server-side rendering (SSR) which lacks access to the client-provided window object.

If needed, you can disable SSR by adjusting settings in a +layout.ts/+page.ts file:

export const ssr = false;

Consider if you truly require the vector implementation from p5 for your project.

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

Exploring the Module System of TypeScript

I am working with a TypeScript module structured like this: let function test(){ //... } export default test; My goal is for tsc to compile it in the following way: let function test(){ //... } module.exports = test; However, upon compilation, ...

Steps for specifying the required type of an Object literal in Typescript

Let's analyze a straightforward code snippet interface Foo{ bar:string; idx:number; } const test1:Foo={bar:'name'}; // this is highly recommended as it includes all required fields const test2={bar:'name'} as Foo; // this is ...

Tips for reorganizing the files within a directory using Visual Studio Code

Is there a way to reformat an entire project folder at once, rather than just one document? I know that I can use the shortcut key Alt+Shift+F or right click on a document and select Format Document. My projects consist of Typescript files in the Angular ...

PrimeNG's Angular component pTree TreeNode

Is there a way in Angular to retrieve the positions of nodes within a TreeNode hierarchy based on their display order? I have data structured as TreeNode objects, which include children that can branch off further. How can I access these nodes according t ...

Utilizing Angular 2: Implementing a template-driven form to send data from a chosen element to the submitting object

Hey there! I'm fairly new to Angular 2 and have been trying to tackle this issue for a while now. I have a user object that contains another nested object, defined by the User interface: export interface UserModel{ name: string, service: Service ...

Innovative techniques for class manipulation

Is there a way to implement type checking when extending a class with dynamic methods? For example, if you want to add methods to a class based on options provided to the constructor. This is a common scenario in plain JavaScript. const defaults = { dyn ...

Error in unit testing: Trying to access property 'pipe' of an undefined variable results in a TypeError

Recently, I've been faced with the challenge of writing a unit test for one of the functions in my component. The specific function in question is called 'setup', which internally calls another function named 'additionalSetup'. In ...

The Material UI Datagrid is failing to display any data

I'm currently facing a challenge that has left me scratching my head. I've implemented Material UI Datagrids, but for some reason, I can't get it to populate with data, and the reason eludes me. Even though the Component profiler shows that ...

Arranging React Grid Items with Stylish Overlapping Layout

Is there a way to create a react-grid-layout with 100 grid points width, while ensuring that the grid items do not overlap? https://i.sstatic.net/CQiVh.png (Reducing the number of columns can prevent overlap, but sacrifices the 100-point width resolution ...

Using the ternary operator for rendering components in TSX: A beginner's guide

Currently, I am retrieving data from a server. The component to display is determined based on the result of this retrieval process. const response = fetch(url) .then((result) => result.json()) .then((data) => data) .catch((e) => { ...

how to adjust the width of a window in React components

When attempting to adjust a number based on the window width in React, I encountered an issue where the width is only being set according to the first IF statement. Could there be something wrong with my code? Take a look below: const hasWindow = typeof ...

Defining data types for an array of objects in a useState hook

I'm having trouble understanding the issue with my code. interface dataHistory { data: string, before: string | number, after: string | number, } I have an interface defined outside of the Functional Component and inside I specify its struct ...

JS The clipboardData in ClipboardEvent is perpetually void

I am trying to retrieve files using CTRL+V from the ClipboardEvent in Angular6, but I am encountering an issue where the clipboardData is always empty regardless of whether I test images or text. This problem persists even when tested on the latest release ...

Ensure that selecting one checkbox does not automatically select the entire group of checkboxes

Here is the code I'm using to populate a list of checkboxes. <label class="checkbox-inline" ng-repeat="item in vm.ItemList track by item.id"> <input type="checkbox" name="item_{{item.id}}" ng-value="{{item.id}}" ng-model="vm.selectedItem" /& ...

I am in need of a customized 'container' template that will display MyComponent based on a specific condition known as 'externalCondition'. MyComponent includes the usage of a Form and formValidation functionalities

container.html <div ngIf="externalCondition"> <!--Initially this is false. Later became true --!> <my-component #MyComponentElem > </my-component> <button [disabled]= "!myComponentElemRef.myDetailsF ...

The data type 'Observable<any>' cannot be assigned to the type 'StoresSummaryResults'. The property 'Data' is not present in the 'Observable<any>' type

As a newcomer to using the Observable with Angular 2, I am facing an issue where my structure is not receiving the results despite being able to validate the response from my REST API. Below is the data class in Typescript that I have: import { RESTResul ...

Tips for including multiple directives in a component

Apologies in advance for my lack of clarity in expressing this question, which is why I am seeking assistance rather than finding the solution on my own. My query pertains to loading a component within another one and specifying it in the directive. Below ...

Developing a personalized validation function using Typescript for the expressValidator class - parameter is assumed to have a type of 'any'

I'm seeking to develop a unique validation function for express-validator in typescript by extending the 'body' object. After reviewing the helpful resource page, I came across this code snippet: import { ExpressValidator } from 'expre ...

What could be causing the sorting function to malfunction on certain columns?

My table's column sorting feature works well with first name and last name, but it seems to have issues with dl and dl score columns. I need assistance in fixing this problem. To access the code, click here: https://stackblitz.com/edit/angular-ivy-87 ...

Error Message: "Module not found - Module TS2307 cannot be located

When I try to open a Typescript project in VSCode, I encounter the error message "ts2307 Cannot find module 'react' or its corresponding type declarations". However, everything works fine when I use WebStorm. The project was created using Create ...