🎁

12 Days of Baddass Courses sale! Get instant access to the entire egghead library of courses and lessons for 58% off.

Runs out in:
15 : 05 : 50 : 24
1×
Become a member
to unlock all features
Autoplay

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

    Nik GrafNik Graf
    rustRust
    javascriptJavaScript

    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.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Discuss

    Discuss

    Transcript

    Transcript

    Instructor: 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.

    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.

    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.

    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.

    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.

    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.