Create and Publish a NPM Package Containing Rust Generated WebAssembly using wasm-pack

Nik Graf
InstructorNik Graf

Share this video with your friends

Send Tweet
Published 4 years ago
Updated 3 years ago

wasm-pack is a tool that seeks to be a one-stop shop for building and working with Rust generated WebAssembly that you would like to interop with JavaScript. This includes ability to publish modules so that you can share your Rust generated WebAssembly code with others.

In this lesson we create a npm package and export a Rust function that will log to the console in the browser. We publish the module to NPM and afterwards use a rust-webpack-template to install and use the newly published package.

Instructor: [00:01] We start out by creating a new Rust library. In our Cargo.toml, we set the create type to be CDY lib, and add the dependency, wasm-bindgen. Right after that, we switch to our Rust lib file and remove the existing code.

[00:21] We declare that we use the create wasm-bindgen, import the function console.log, and export the function greet, accepting a name. Next up, we run wasm-pack build. Don't be surprised, this might take a couple minutes.

[00:45] This creates a package directory. In previous lessons, I mentioned that it contains a WASM and a Javascript file. What I haven't mentioned yet is that it also creates a package.json based on our Cargo.toml.

[00:59] Using wasm-pack publish, we can publish this package to NPM, and use it in any app supporting WASM. For example, a Rust webpack template. Keep in mind, you need to use wasm-pack login to log into NPM. I did this before I started the lesson.

[01:21] Let's verify that this actually works. We switch over to our Rust webpack project and install our package, myWasmLib. Then we open the index.js file of our application, and add an import to our just-published library.

[01:43] Once our libary's imported, we can import the greet function we previously exported. In the browser, we now can see "Hello World." This means we can use any library using WebAssembly in our code, as well as we can publish our own using wasm-pack.