Autocomplete and documentation for "imported" p5js

When we use import in JS 2 things happen:

  1. The file becomes a JS module and it needs a <script type=module> to load inside the HTML.
  2. JS checks the import line if a file w/ that exactly path & name exists so it can load it as a module.

As we can note the file “ml-matrix” doesn’t exist.
Instead there are “matrix.js” & “matrix.umd.js”.
However neither is a JS module but just vanilla JS code.

The library’s types is called “matrix.d.ts”.
But to make things worse “matrix.umd.js” is exposed as namespace mlMatrix, while “matrix.d.ts” exposes its main class as Matrix.

It doesn’t seem very feasible to have at the same time types when coding & auto deployment w/o the trouble of manually commenting & uncommenting the line w/ import.
Unless you code some script which automatically do that toggling magic for you.

Anyways, I’ve found a workaround for it.
However you’re gonna need to switch to TypeScript in order to pull that out.

TypeScript automatically skips any import statements when transpiling our code to JavaScript as long as we just use those imports as datatypes and never as the actual thing.

The main workaround are these few lines below:

import * as p5 from "p5";
import {} from "p5/global";

import * as mlmtx from "ml-matrix";

declare var mlMatrix: typeof mlmtx;

After those lines we can freely use mlMatrix as a namespace for the whole “ML-Matrix” library.

And none of those lines will show up at the transpiled JS file!

Check the simple example online at this link:
GoToLoop.GitHub.io/ML-Matrix-P5JS-Template

And visit the repo to download the whole code release:

3 Likes