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 d.ts
file,
a .wasm
file and a .js
file in ES6 module format.
2 Set up the TypeScript code
Now we should set up a JavaScript project.
- Run
npm init
to create an npm project. - Run
npm i -D typescript
to install tsc - Run
npx tsc --init
to create atsconfig.json
file - For cleaner organization of our source code, let’s say all ts files should be put in a specific
ts/
directory - Edit the
tsconfig.json
file. 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 init()
first,
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:
Run
|
|
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
this issue
for some discussion).
4 Set up a production build process
Most of the important outputs should be in /build
and /pkg
. For deployment, it’s
pretty easy to use any standard bundling tool to build a single bundle out of the
generated 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
src
attribute in the html file withsed
or other fancy tools as part of our build process - The generated
.js
file fromwasm-pack
assumes that thewasm
file will be adjacent. We can either ensure that this happens, or pass in the path to thewasm
file when calling theinit
function.