Photo by Paola Aguilar on Unsplash
There is only one prerequisite for this tutorial - installed Docker. Well, also you will need a good internet connection because of rust image which weights 1.7Gb
docker run -v "$PWD":/usr/src/myapp -w /usr/src/myapp --rm --interactive --tty stereobooster/rust-wasm
USER=stereobooster cargo generate --git https://github.com/rustwasm/wasm-pack-template
cd wasm-nanoid
wasm-pack init
Use your GitHub handle instead of mine (USER=stereobooster
). Use your name of the project instead of mine (wasm-nanoid
).
This is it. Your development environment ready. Keep reading to know how to write and test package.
Develop
Edit Cargo.toml
:
description = "nanoid implemented in wasm"
repository = "https://github.com/stereobooster/wasm-nanoid"
license = "MIT"
Edit README.md
. Add to .gitignore
:
*.log
pkg/*
Commit (you may want to do this in an OS shell because git inside Docker is not configured).
git add .
git commit -m "initial commit"
I want to build the simple thing, so I will reuse the existing Nano ID package (crate).
Add dependency to Cargo.toml
:
js-sys = "0.2.6"
nanoid = "0.2.0"
Edit src/lib.rs
:
extern crate cfg_if;
extern crate wasm_bindgen;
extern crate js_sys;
// import nanoid module
extern crate nanoid;
// for [wasm_bindgen] instruction
use wasm_bindgen::prelude::*;
// the function itself
#[wasm_bindgen]
pub fn simpleNanoid() -> js_sys::JsString {
// generate nanoid and convert value (str) to JsString
js_sys::JsString::from(nanoid::simple())
}
To build run in docker shell:
wasm-pack init
Setup testing environment
Run in OS shell:
npm init wasm-app example
create package.json
in the root of the project:
{
"private": true,
"workspaces": ["*"]
}
Edit .gitignore
(add):
node_modules
Edit example/package.json
:
"devDependencies": {
"wasm-nanoid": "^0.1.0",
...
}
Now run the example:
cd example
yarn
yarn start
Publish
If you want to publish run in OS shell, where your npm credentials are configured:
cd pkg
npm publish
Result
In my case I got (in example apps console):
Error importing `index.js`: RuntimeError: unreachable
at __rust_start_panic (wasm-function[79]:1)
and wasm_nanoid_bg.wasm
is 50Kb but at least it was easy to create, test and publish my first (not working) WASM npm package. Will get back to tutorial.
Code from this post published here.