How can i import p5.js into TypeScript?

Viewed 4429

I'm trying to start a project in typescript and wanted to use the p5.js library. Is there any way to "import" the library into my index.ts file, so that I don't need to put <script src="p5.js"></script> in the HTML. I'm new to modules. Thanks in advance.

2 Answers

I think there are packages p5 available on npm you can use:

Install

npm i p5 @types/p5

// Or yarn

yarn install p5 @types/p5

Then import thing you want to use:

import { Camera } from 'p5';

You could add this:

<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.1.9/p5.js"></script>, like in here:

<!DOCTYPE html>
<html>
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.1.9/p5.js">
  </head>
  <body>
    <script src="your_code.js"></script>
  </body>
</html>


I'm sorry, but this is the only way to do this, unless you are using an online editor like PlayCode.io, if it is the case, you could go to the left sidebar and type p5.js in LIBS +. And to make the editor TypeScript, go to the up right corner of the editor —not the page— and click the button that says [JS], then select the language you want.



I hope this answer of mine was helpful.

Related