Using p5.js with TypeScript and Webpack is not supported

I'm currently working on a library project that involves utilizing p5.js.

Specifications

Here is a snippet of my Webpack configuration:

const path = require('path');

module.exports = {
    entry: './start.ts',
    output: {
        filename: 'start.js',
        path: path.resolve(__dirname, 'out'),
        libraryTarget: "var",
        library: "at",
    },
    resolve: {
        extensions: ['.ts', '.tsx', '.js', '.jsx']
    },
    module: {
        rules: [
            {
                test: /\.ts$/,
                loader: "awesome-typescript-loader"
            }
        ]
    }
};

This is how my package.json looks like:

{
  ...,
  "scripts": {
    "build": "./node_modules/.bin/webpack --config webpack.config.js"
  },
  "devDependencies": {
    "awesome-typescript-loader": "5.0.0",
    "typescript": "2.8.3",
    "webpack": "4.9.1",
    "webpack-cli": "2.1.4"
  },
  "dependencies": {
    "p5": "0.6.1"
  }
}

To incorporate typescript, I've configured my tsconfig.json as follows:

{
  "compilerOptions": {
    "noImplicitAny": true,
    "noEmit": true,
    "sourceMap": true,
    "target": "es5",
    "module": "es2015",
    "lib": [ "dom", "es5" ],
    "baseUrl": "."
  },
  "include": [
    "start.ts",
  ],
  "exclude": [
    "out"
  ]
}

The entry point in start.ts is defined like this:

import * as p5 from "p5";

class entry {
    // Some
}

Issue

I'm encountering an issue with finding p5 in IntelliSense using VSCode. Upon running npm run build, the following error occurs:

> webpack --config webpack.config.js

[at-loader] Using <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="22565b52475141504b525662100c1a0c11">[email protected]</a> from typescript and "tsconfig.json" from C:\Users\me\Documents\GitHub\myproj/tsconfig.json.

... (additional warning and error messages)

ERROR in [at-loader] ./start.ts:1:21
    TS2307: Cannot find module 'p5'.

... (more npm error logs)

Can anyone provide insight into what might be causing this issue?

Answer №1

Upon investigation, it appears that the 'p5' typings are incorrect and cannot be used as is. To understand more about these issues, please refer to this link: https://github.com/processing/p5.js/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen+typescript

In your case, there seems to be a configuration error causing problems. You can identify the specific error by creating an index.ts:

import 'p5'
console.log(p5)

and attempting to transpile it using tsc:

node_modules/p5/lib/p5.d.ts(555,19): error TS2304: Cannot find name 'COLOR_MODE'.
node_modules/p5/lib/p5.d.ts(871,87): error TS2304: Cannot find name 'ARC_MODE'.

... some errors have been omitted for brevity

node_modules/p5/lib/p5.d.ts(10312,5): error TS2416: Property 'amp' in type 'Noise' is not assignable to the same property in base type 'Oscillator'.
  Type '(volume: number | object, rampTime?: number, timeFromNow?: number) => void' is not assignable to type '(vol: number | object, rampTime?: number, timeFromNow?: number) => AudioParam'.
    Type 'void' is not assignable to type 'AudioParam'.

Given that p5 is utilized globally and there doesn't seem to be a clear module-based example available, you can resolve this issue by following this approach:

// index.ts
declare const p5: any
// code away

Answer №2

If you're looking for real typing in p5.js, the official typings package is available. Simply use npm i @types/p5 --save-dev to install it instead of resorting to the any type workaround suggested by unional.

You can find the typings package on npm at: https://www.npmjs.com/package/@types/p5

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

Implementing TypeScript for augmented styling properties in a component - a guide

I have custom components defined as follows: import React from 'react'; import styled from '../../styled-components'; const StyledInput = styled.input` display: block; padding: 5px 10px; width: 50%; border: none; b ...

Pausing or buffering an RxJS 6 observable when the page is inactive

Currently, I am dealing with a stream of letters that need to be arranged in the correct order to form a word. However, an issue arises when the user switches tabs, minimizes the browser, or switches applications - the behavior mimics using setTimeout(), r ...

A more efficient method for querying documents based on ids that are not in a given list and then sorting them by a specific publish date

After implementing the code provided below, I noticed that the performance tests indicate each request takes a second or longer to complete. My goal is to enhance this speed by at least 10 times. The bottleneck seems to be caused by the NOT operator resu ...

Why is it that TypeScript struggles to maintain accurate type information within array functions such as map or find?

Within the if block in this scenario, the p property obtains the type of an object. However, inside the arrow function, it can be either an object or undefined. const o: { p?: { sp?: string } } = { p: {} } if (o.p) { const b = ['a'].map(x => ...

`Why TypeScript in React may throw an error when using a setter`

As I work on building a small todo app in TypeScript with React, I encountered an issue when attempting to add a new todo item to my list. It seems like the problem may lie in how I am using the setter function and that I need to incorporate Dispatch and s ...

What is the best way to send {...rest} properties to a text field in react material?

When using a material textfield inside a wrapper component and passing the remaining props as {...otherprops} in a JavaScript file, everything works fine. However, when attempting to do the same in TypeScript, an error occurs. const TextFieldWrapper = (pro ...

The page does not appear to be updating after the onClick event when using the useState hook

Having difficulty re-rendering the page after updating state using the useState hook. Although the state value changes, the page does not refresh. export function changeLanguage(props: Props) { const [languageChange, setLanguageChange] = React.useState( ...

Is it possible that jest is unable to catch the exception?

I have a simple function that looks like this: function foo({ platform }) { if (platform === 'all') { throw new Error('Platform value can only be android or ios'); } return `${platform}`; } After writing unit tests, the re ...

Is it possible to combine JavaScript objects using TypeScript?

Currently, I am dealing with two objects: First Object - A { key1 : 'key1', key2 : 'key2' } Second Object - B { key1 : 'override a' } I am looking to combine them to create the following result: The Merged Re ...

Adding data-attributes to a Checkbox component using inputProps in React

Utilizing Fabric components in React + Typescript has been a breeze for me. I have been able to easily add custom attributes like data-id to the Checkbox component, as documented here: https://developer.microsoft.com/en-us/fabric#/components/checkbox Howe ...

The presence of v-if does not depend on the model value to toggle the element

I have a scenario where I want to hide the dropdown menu for US states if a different country other than the US is selected. The code snippet I am using to achieve this functionality is shown below: <b-row v-for="demo in demographics" :key=&qu ...

Avoiding useCallback from being called unnecessarily when in conjunction with useEffect (and ensuring compliance with eslint-plugin-react-hooks)

I encountered a scenario where a page needs to call the same fetch function on initial render and when a button is clicked. Here is a snippet of the code (reference: https://stackblitz.com/edit/stackoverflow-question-bink-62951987?file=index.tsx): import ...

Determining data types through type guarding in Typescript

interface A = { name: string; ... }; interface B = { name: string; ... }; interface C = { key: string; ... }; type UnionOfTypes = A | B | C | ...; function hasName(item: UnionOfTypes) { if ("name" in item) { item; // typescript knows ...

What is a more efficient way to write nested subscribe in Angular?

I am a beginner with RxJS and I'm interested in learning how to write clean code using it. I currently have a nested subscription that I've been trying to refactor without success. firstMethod() { this.testMethod(name) console.log(this.curren ...

Creating seamless compatibility between the elliptic library in JavaScript and the ecdsa library in Golang for efficient cross-platform operations

I am having issues with validating a signature created using the elliptic JavaScript library and the ecdsa library from Golang. The elliptic curve in question is secp256k1. Below are some snippets of code: Here are the TypeScript utility functions: impor ...

Tips for displaying an array and iterating through its children in Angular 7

I am currently working on extracting the parent and its children to an array in order to display them using ngFor. However, I am encountering an issue where the children are not being displayed during the ngFor. I have a service that retrieves data from a ...

Leverage Async Await for Setting Response Data in TypeScript

Currently, I am making multiple API requests with different data and storing all the responses in an array. Then, I am using .map to map the response array to my original array to update the data. However, it seems like the process is not working correctly ...

Utilize TypeScript in creating a Chrome extension to fetch elements by their ID

I'm currently working on a Chrome extension using Angular and Typescript, and I have encountered an issue with accessing the document element by its id from the active tab. While this works perfectly fine in JavaScript, I am facing difficulties in ach ...

What is the best method for accessing the properties of a JavaScript object based on input from a textbox?

Just starting out with angular and having trouble generating or updating a table based on text boxes. The schema includes country, sales, and profit fields. There are two text boxes for the x-axis and y-axis inputs. The table should dynamically update when ...

In order to handle this file type, make sure you have the right loader set up for Preact

Help! I'm struggling with a React issue and need some assistance. I've searched through various posts but haven't found a solution yet, so I'm turning to you for help. I am working with simple React on a webpack-dev-server, and when tr ...