1 Set up the rust code and wasm-pack
- install wasm-pack
- Set up a new project with wasm-pack. Run
- Build with this command
This should produce a
pkg/ directory which should contain some
.wasm file and a
.js file in ES6 module format.
2 Set up the TypeScript code
npm initto create an npm project.
npm i -D typescriptto install tsc
npx tsc --initto create a
- For cleaner organization of our source code, let’s say all ts files should be put in a specific
- Edit the
tsconfig.jsonfile. Here are the field values we should make sure to update
For our little demo purpose, we will call the demo
greet() function from the generated rust project.
Let’s make a file
ts/entry.ts, with the following content:
This mostly follows the official guide .
It’s a bit tricky here because TypeScript won’t prevent you from calling
greet() without calling
but doing so will lead to a crash. This is something to keep in mind, though it’s not specific to our setup.
Next we verify that this builds:
3 Set up a development iteration process
Now let’s set up an actual html file.
Next, we can use any quick static server iterate on our code. I will use
live-server here as an example:
On another terminal, run
Now making any changes in the typescript should trigger a rebuild and an autoreload.
Unfortunately there isn’t a
watch mode for
wasm-pack yet as of April 2021 (see
for some discussion).
4 Set up a production build process
Most of the important outputs should be in
/pkg. For deployment, it’s
pretty easy to use any standard bundling tool to build a single bundle out of the
entry.js file. There are two other small details to take care of
- The html file assumes the build layout - we can fix this by replacing the
srcattribute in the html file with
sedor other fancy tools as part of our build process
- The generated
wasm-packassumes that the
wasmfile will be adjacent. We can either ensure that this happens, or pass in the path to the
wasmfile when calling the