G4js - developing a new GUI library for p5.js (now called canvasGUI)

  • Formally I used Atom.io w/ some extensions for TS.
  • But currently I’m in VSC, which got good TS support out-of-the-box.
  • I also have both NodeJs.org & Git installed to deal w/ NPM packages & GitHub repos.

Well, I’ve ended up creating a p5js library template repo just to answer that:

After unpacking the downloaded project file:

  • Double-click file “setup.bat” so it creates the subfolder “node_modules/” and globally installs the TS compiler “tsc”, the local file server “serve”, the p5js library itself, plus its type definitions; all that based on “package.json” contents.
  • That template project has a “tsconfig.json” file which instructs “tsc” to automatically compile every TS file inside subfolder “src/” and output them into subfolder “dist/”; plus their type definitions into subfolder “typings/”.
  • In this particular template example I have a class Ball defined in file “dist/ball.mts” which is gonna act as a p5js library addon.
  • Also a helper “dist/attribute.mts” file which is imported by “dist/ball.mts”.
  • FYI, “.mts” is a new file extension which explicitly defines it as an ECMAScript Module: 16. Modules
  • The “tsc” compiler will automatically output “.mts” files as “.mjs” btW:
  • The last subfolder to discuss is “tests/”, which contains 2 other subfolders “regular/” & “import/”.
  • In total there are 4 “.js” files as test example sketches on how to consume the “dist/ball.mjs” library.
  • Subfolder “tests/regular/” got files “sketch.js” & “sketch.instance.js”.
  • “tests/regular/sketch.js” is a typical p5js sketch in global mode style.
  • And “tests/regular/sketch.instance.js” is like the former above, but using instance mode style instead.
  • It’s super important that a p5js library addon be compatible w/ both global & instance modes.
  • The other 2 sketches in subfolder “tests/import/” teach how to import the “dist/ball.mjs” library directly in code w/o using a <script> tag in an HTML file:
  • The “index.html” file loads both sketches from subfolder “tests/regular/”.
  • It adds the attribute “data-ball-auto-import” to the “dist/ball.mjs” <script> tag.
  • The library searches all <script> tags for that “data-ball-auto-import” attribute.
  • When it’s found, it automatically exposes its class Ball to globalThis.
  • And it also adds the alternative method createBall() to the p5 class.

That’s all for now! Hope it helps you to develop your g4js addon library in TS using ES6 modules:

2 Likes