[Pas2js] Importing Known Javascript packages

Michael Van Canneyt michael at freepascal.org
Wed Jan 5 01:58:13 CET 2022


Hello,

Most people will be aware that you can use external Javascript packages if
you create an import unit for it. Pas2js ships with several such import
units.

Making such a unit is tedious work.

Fortunately, there is now a solution.

Typescript is a typing system on top of Javascript, made by Microsoft.
Typescript is becoming more and more the de-facto way to program Javascript
for Javascript programmers.
It simply checks your code and transpiles to Javascript. Much like pas2js.

Typescript programmers have the same problem as Pas2js programmers:
How to use all the Javascript libraries out there ?
Many modern Javascript libraries provide an import description for
Typescript. But not all.

Luckily, there is a large library of "import libraries" for many popular
Javascript APIs (they call it Typescript declaration modules), called
DefinitelyTyped:

https://github.com/DefinitelyTyped/DefinitelyTyped

Using these, a Typescript programmer can use many popular Javascript
libraries (around 10.000, if my count is accurate).

How does this help us ?

FPC, since a long time has a Javascript parser component.
This has now been extended to be able to parse Typescript.

We went a step further, and convert the TypeScript type declarations to pascal.

The result is that we can take a TypeScript declaration file 
(a *.d.ts file) for some Javascript library, and create an import file,
automatically.

Better yet, the tool has been put in a CGI program, and is available online;

https://www.freepascal.org/~michael/pas2js-demos/ts2pas/

Just type the name of some Javascript library. If it is in DefinitelyTyped,
then the name will appear in the list. Selecting the correct file and
pressing "Go" will convert the file for you: a ready made pascal import
unit.

The tool is not perfect, but it will take 99% of the work out of your hands.
It parses 99.5% of all files in DefinitelyTyped.

>From the 7500 files I tested with the conversion tool, only 50 fail to convert. 
More than 2000 generated files compile out-of-the box. The rest will need
some tweaking.

For example: when a file uses the Javascript import mechanism, this is not
yet taken into acoount, and you will most likely encounter an 
'Identifier not found' error. In many cases, this can be remedied by running
the tool on the imported file, and adding the generated unit to the uses clause.

The tool is committed in the FPC repository.
It will still be improved, just as the online version,  but can already be used quite well today.

Enjoy !

Michael.



More information about the Pas2js mailing list