Import / Reference Rust WASM functions from dynamically named JavaScript module

  • I created a simple Rust project using wasm-bindgen.
  • I am using trunk to build and serve the project locally.
  • I added a JavaScript module myapp.mjs and then <link> it from index.html.
  • When I build the project, trunk generates a JS wrapper for the WASM file, with an unpredictable name

:thinking: Question: How do I import a Rust function from front-end-f47407f6508404f8.js dynamically?

My thought is that I would do:

import { do_something } from './dist/front-end-xxxxxxxxx.js';

However, every time I make a change to my lib.rs file, the name of the target JavaScript file in the dist/ folder changes (presumably some hashing function).

What's the correct way to reference the WASM JS wrapper from my application's JS module?

I found the solution, although I'm not sure if it's the "correct" solution or not.

According to the Trunk App Setup, your assets are injected into the resulting index.html file underneath the dist/ directory.

All of the Rust function bindings are dynamically imported and assigned to the window.wasmBindings property.

In my (or your) application code, you can simply call any Rust function with:

window.wasmBindings.my_function_name(param1, param2);

This is the snippet on the website that does the import and assignment of all bindings to window.wasmBindings:

import init, * as bindings from '/index-7eeee8fa37b7636a.js';
window.wasmBindings = bindings;
init('/index-7eeee8fa37b7636a_bg.wasm');

I don't currently see anywhere in the Trunk documentation where they tell you that your Rust functions can be called using the window.wasmBindings reference, hence my confusion.