Programming

Notes on calling Rust from Javascript

Although the tutorial looks great and comprehensive it describes a process that is surprisingly cumbersome. If you switch to the modern web approach things seem to get a lot simpler. This simply requires you to set the target of the output to be web.

With this done and a little bit of boilerplate (which I need to extract and make reusable somehow) which consisted of a static page, a one-line dynamic import Javascript file (which I’m not sure is needed) and a variant of the generated bootstrap file I was able to write any pure function using numbers or strings in Rust and then use it in short-order in the static page.

wasm-pack outputs a lot of files, there is the WASM binary itself which seems straight-forward, a couple of Typescript definition files which I presume is to help integrate the output into Typescript projects if you’re shipping the output as a module. There are two Javascript files that seem to define the Javascript version of the Rust functions and the value conversion between the two languages. I’m not sure why there are two, I might need to do a clean build and see what comes out. Maybe the smaller Javascript file actually contains everything needed for the web.

The way things feel at the moment is that if you’re stuck with a build issue the errors and the solution can feel incomprehensible but once it works it works really well and it is shockingly easy to export callable functions.

Apart from trying to find the minimum viable build I also need to try and implement something that is a bit more computationally challenging in the Rust function and get a sense of what the overhead of the Web Assembly call is because it feels relatively minimal.

Standard